简体   繁体   中英

Starting Objective-C, memory leak concerns

Hey guys, I'm starting to play around with Objective-C and I want to make sure I get memory/properties right.

Suppose the following code:

@interface Rectangle : NSObject 
{
    Vector2* origin;
    //[...]
}

Rectangle* myRect  = [[Rectangle alloc] init];
myRect.origin.x = 100.0f;
[myRect print];
myRect.origin = [[Vector2 alloc] init]; //hummm.. 2 concerns here.

Concern 1:

Suppose origin is a standard (assign) synthesized property:

Does myRect's previous origin ref count goes to 0 automatically when assigning the new Vector2 and GC will take care of it later on? Or I have to call release explicitly inside the property?

Concern 2:

Suppose origin would be a 'retain' property: (BTW: Would that kind of code be automatically generated when declaring a synthesized retain property, is that possible?)

-(void) setOrigin: (Vector2*)newOrigin {
   [newOrigin retain];
   [origin release]
   origin = newOrigin;
}

Then when doing:

myRect.origin = [[Vector2 alloc] init]

Wouldn't that cause a double ref count increment and then needing release to be called twice to avoid leak? Do you guys rely on well-documented code (to know it's a retain property) when using libraries/other people's code to avoid such problems, or is there some safer ways of alloc/init objects?

Thanks for tips!

Concern 1:
[...] Does myRect's previous origin ref count goes to 0 automatically

No, an assign property does just what it says - assign. It doesn't retain nor release - you have to handle that manually in that case.

Concern 2:

myRect.origin = [[Vector2 alloc] init]

Wouldn't that cause a double ref count increment

Yes, thats why you'd either use autorelease:

myRect.origin = [[[Vector2 alloc] init] autorelease];

... or manually release it:

Vector2 *v = [[Vector2 alloc] init];
myRect.origin = v;
[v release];

As for how to manage those problems:

  • read the memory management guide
  • look what the documentation or the property declaration says
  • for parameters passed to methods always assume the callee retains if needed - unless documented otherwise

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM