proper memory handling for an NSMutableArray assigned to property?

↘锁芯ラ 提交于 2019-12-31 06:57:28

问题


I have a property declared like this:

@property (nonatomic, retain) NSMutableArray *pricingLevels;

And I assign it like this:

 self.pricingLevels = [[[NSMutableArray alloc] init];

in my dealloc I have this:

self.pricinglevels=nil;

When I analyze my code with xCode it says I have a memory leak here:

self.pricingLevels = [[[NSMutableArray alloc] init];

Should I be using an autolrelease on this because the self.pricinglevels holds a reference to the array also?


回答1:


self.pricingLevels is a property declared as retained which means every time you set it thru property assignment (the dot-syntax OR the method), the object automatically retains the object for you.

self.pricingLevels = [NSMutableArray array];
[self setPricingLevels:[NSMutableArray array]];

The above code will do the same and automatically retain the array passed. This is what happens under the hood (or something similar). This method gets called:

- (void)setPricingLevels:(NSMutableArray *)a {
    if(_pricingLevels != a) {
        [_pricingLevels release];
        _pricingLevels = [a retain];
    }
}

You see? Automatically retained, while the previous value automatically gets released.

EDIT to answer your last question: Yes you should call autorelease




回答2:


Yep, you have a memory leak. Assigning to self.propertyName for a retained property automatically performs a retain. You either need to release the object after assigning (slightly more efficient to just do release after assigning vs using autorelease), or you need to assign the retained object to the instance field (sans self.) not the property name, AND, for this latter case, you need to be sure that the instance field was previously nil (ie, only do the direct assignment in initialization logic).

(And don't forget your dealloc method.)

(This all has nothing to do with the fact that the object happens to be an NSMutableArray.)




回答3:


The issue is while initializing and releasing you shouldn't use self infront of the variable

self.pricingLevels = [[[NSMutableArray alloc] init];
//instead it should be

pricingLevels = [[[NSMutableArray alloc] init];

even on releasing it should be

[pricingLevels release];
pricingLevels = nil;


来源:https://stackoverflow.com/questions/8605078/proper-memory-handling-for-an-nsmutablearray-assigned-to-property

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