开发者

NSMutableArray memory leak

XCode is reporting a memory leak on a specific line of code:

(NSArray*)myFunction{
   NSMutableArray * tempMapListings=[[NSMutableArray alloc] init]; //Xcode says leak is here

   //do a bunch of stuff to insert objects into this mutable array


    return tempMapListings;
    [tempMapListings release]; // but I release it ?!

   }

Is this due to releasing as an NSArray an mutable array? Since mutable inherits from inmutable, I wouldn't think this is a problem, and in any c开发者_如何转开发ase, the object is released anyway. I'd appreciate the advice of a second eye.


No you're not releasing it. The return statement really ends the execution of the method at that point. So, the line below it, in your case

[tempMapListings release]; // but I release it ?!

is not executed.

Instead, you use autorelease:

-(NSArray*)myFunction{
    NSMutableArray * tempMapListings=[[NSMutableArray alloc] init];
    //do a bunch of stuff to insert objects into this mutable array
    return [tempMapListings autorelease];
}

You can learn about autorelease in many places. Look for it in Apple's own documentation; you can also google it.


You're releasing tempMapListings after your return from the function. After a return statement, no more code is executed on that branch. Ergo, your [tempListListings release] statement is never run. Moreover, as you're returning it, you don't actually want to release it straight away - the caller will never have a chance to retain the array!

Autorelease pools are your friend here. Objects added to an autorelease pool are released on your behalf "eventually", giving your caller time to grab the result. To add your object to the default pool, change your allocation line to

NSMutableArray *tempMapListings = [[[NSMutableArray alloc] init] autorelease];

and remove that last release call.

For more information on autorelease pools, have a read of Apple's documentation. They're really quite useful.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜