分配给属性的 NSMutableArray 的正确内存处理?
我有一个这样声明的属性:
@property (nonatomic, retain) NSMutableArray *pricingLevels;
我这样分配它:
self.pricingLevels = [[[NSMutableArray alloc] init];
在我的 dealloc 中我有这样的:
self.pricinglevels=nil;
当我用 xCode 分析我的代码时,它说我这里有内存泄漏:
self.pricingLevels = [[[NSMutableArray alloc] init];
我应该使用 autolrelease
这是因为 self.pricinglevels
还保存了对数组的引用?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
self.pricingLevels
是一个声明为retained
的属性,这意味着每次通过属性赋值(点语法或方法)设置它时,对象都会自动保留该对象你。上面的代码将执行相同的操作并自动保留传递的数组。这就是幕后发生的事情(或类似的事情)。这个方法被调用:
你看到了吗?自动保留,而之前的值自动释放。
编辑回答你的最后一个问题:是的,你应该调用
autorelease
self.pricingLevels
is a property declared asretained
which means every time you set it thru property assignment (the dot-syntax OR the method), the object automatically retains the object for you.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:
You see? Automatically retained, while the previous value automatically gets released.
EDIT to answer your last question: Yes you should call
autorelease
是的,你有内存泄漏。为保留属性分配 self.propertyName 会自动执行保留。您要么需要在分配后释放对象(与使用
autorelease
相比,在分配后执行release
效率更高),或者需要将保留的对象分配给实例字段(sansself.
) 不是属性名称,并且,对于后一种情况,您需要确保实例字段之前为 nil(即,仅在初始化逻辑中进行直接赋值)。(并且不要忘记你的dealloc方法。)
(这一切与该对象恰好是一个NSMutableArray这一事实无关。)
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 usingautorelease
), or you need to assign the retained object to the instance field (sansself.
) 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.)
问题是
在初始化和释放时,您不应该在变量前面使用 self,
即使在释放它时也应该如此
The issue is
while initializing and releasing you shouldn't use self infront of the variable
even on releasing it should be