简体   繁体   中英

What are the difference between following 2 lines of Objective C code?

@interface Foo : NSObject

@property (nonatomic, retain) Bar * bar;

@end

@implementation Foo

@synthesize bar = _bar;

- init {
    self = [super init];
    if (self) {

        _bar =  [[Bar alloc] init];

        // Or 

        _bar =  [[[Bar alloc] init] autorelease];


    }
    return self;
}

- (void)dealloc {
    [_bar release];
    [super dealloc];
}

@end

When I run the analyzer, both

        _bar =  [[Bar alloc] init];

and

        _bar =  [[[Bar alloc] init] autorelease];

are fine.

Which one I should use?

You should use the first. It creates a retained object, whereas the second "autoreleases" that retain.

The important consideration is that you're assigning it to instance variable _bar. If you were, instead, assigning it to property self.bar , then the retain directive in the property declaration would cause the object to be retained, so assigning an autoreleased value would be appropriate. But since you're assigning to the "bare" instance variable instead, you need to handle the retain yourself, so you need the first form.

PS: I'm a bit surprised that the analyzer doesn't complain about the second version.

PPS: It should be noted that the choice here is highly context dependent. But you included enough context (the property definition) to make the choice. Without seeing the property definition (or other info, in the case of a non-property) it would be hard to say.

The autorelease version is not correct and may cause crashes in some situations—your first line results in _bar having a retain count of 1 , and thus sticking around until it's release d in -dealloc when you no longer need it.

The second line, however, releases the object soon-ish (specifically, at the end of the run loop), and thus could cause it to disappear when you still need it.

Read Apple's Guide on Memory Management for more information.

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