-->

Am I leaking this ObjectiveC Object?

2019-08-10 02:37发布

问题:

@interface foo: NSObject
@property (nonatomic, retain) NSMutableArray *aMutableArray;
@end

@implementation
@synthesize aMutableArray

-(void)somefunction {
    // Illustration
    self.aMutableArray = [[[NSMutableArray alloc]init]autorelease];
    self.aMutableArray = [[[NSMutableArray alloc]init]autorelease];
    self.aMutableArray = [[[NSMutableArray alloc]init]autorelease];
}
@end

I have done code similar code to this in other parts of my program, but I needed to be certain that this does not cause a memory leak. With my understanding of autorelease, this object is released correctly right?

[EDIT - added question] One question though: the property above has a retain attribute, so when the compiler creates the setter function, the setter code will look something like this:

somecode..
retain newObj
release oldObj
somecode..

in the code above, I assigned 3 objects to aMutableArray. Each time they are assigned, the setter function did a retain on the newObj and a release on the oldObj. So, since the setter method already did a release, will there be a problem when the autorelease kicks-in to release the object a second time?

回答1:

Yes, it will be released correctly if you also release it dealloc method:

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

Note also that you can shorten your code using equivalent convenience +array method of NSMutableArray:

self.aMutableArray = [NSMutableArray array];