Am I leaking this ObjectiveC Object?

天大地大妈咪最大 提交于 2019-12-11 06:41:32

问题


@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];


来源:https://stackoverflow.com/questions/8553533/am-i-leaking-this-objectivec-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!