我是否泄漏了这个 ObjectiveC 对象?
@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
我在程序的其他部分编写了与此类似的代码,但我需要确定这不会导致内存泄漏。根据我对 autorelease
的理解,这个对象被正确释放了,对吗?
[编辑-添加问题] 但有一个问题:上面的属性有一个保留属性,因此当编译器创建 setter 函数时,setter 代码将如下所示:
somecode..
retain newObj
release oldObj
somecode..
在上面的代码中,我将 3 个对象分配给 aMutableArray。 每次分配它们时,setter 函数都会对 newObj 执行 retain 操作,并在 oldObj 上执行 release 操作。那么,既然setter方法已经做了释放,那么当autorelease启动第二次释放对象时会不会有问题呢?
@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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,如果您还释放了 dealloc 方法,它将被正确释放:
另请注意,您可以使用 NSMutableArray 的等效便捷
+array
方法来缩短代码:Yes, it will be released correctly if you also release it dealloc method:
Note also that you can shorten your code using equivalent convenience
+array
method of NSMutableArray: