Objective-C Properties and Memory Management

Given the following property definition:

@property (nonatomic,retain) MyObject* foo;

Does the following code lead to a memory leak:

self.foo = [[MyObject alloc] init];

?

It looks like the alloc call increments the hold count by 1 to the object, and then holds the properties inside the setterter. But since the initial count never decreases to 0, the object will stick even when self is released. Is this analysis correct?

If so, it looks like I have two alternatives:

self.foo = [[[MyObject alloc] init] autorelease];

which is not recommended for iPhone for performance reasons, or:

MyObject* x = [[MyObject alloc] init];
self.foo = x
[x release];

which is a little cumbersome. Are there other alternatives?

+5
source share
3 answers

, self.foo = [[MyObject alloc] init]; . . autorelease : , , , , , self, .

+2

?

.

iPhone autorelease, Cocoa Touch- . , ( ) .

MyObject, /init/autorelease, .

+ (MyObject *)object {
    return [[[MyObject alloc] init] autorelease];
}

self.foo = [MyObject object];
+3

iPhone - ( , , ):

-(id)init {
    if (self = [super init]) {
        self.someObject = [[[Object alloc] init] autorelease];
    }
    return self;
}

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

autoreleasefrees the link to the floating instance that is assigned self.object, which saves its own link, leaving you the link you need ( someObject). Then, when the class is destroyed, the only remaining reference is freed, destroying the object.

As described in another answer, you can also create one or more “constructor” messages to create and auto-update objects with additional parameters.

+(Object)object;
+(Object)objectWithCount:(int)count;
+(Object)objectFromFile:(NSString *)path;

You can define them as:

// No need to release o if fails because its already autoreleased
+(Object)objectFromFile:(NSString *)path {
    Object *o = [[[Object alloc] init] autorelease];
    if (![o loadFromFile:path]) {
        return nil;
    }
    return o;
}
+3
source

All Articles