Howard
Howard

Reputation: 19815

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?

Upvotes: 0

Views: 114

Answers (2)

Hot Licks
Hot Licks

Reputation: 47729

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.

Upvotes: 4

andyvn22
andyvn22

Reputation: 14824

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 released 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.

Upvotes: 2

Related Questions