我是否泄漏了这个 ObjectiveC 对象?

发布于 2024-12-21 14:17:03 字数 870 浏览 7 评论 0原文

@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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

波浪屿的海角声 2024-12-28 14:17:03

是的,如果您还释放了 dealloc 方法,它将被正确释放:

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

另请注意,您可以使用 NSMutableArray 的等效便捷 +array 方法来缩短代码:

self.aMutableArray = [NSMutableArray array];

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];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文