关于工厂方法对象生命周期在Objective-C / Cocoa的问题(保留或不...) [英] Question about factory method object lifetimes in Objective-C/Cocoa (to retain or not...)

查看:156
本文介绍了关于工厂方法对象生命周期在Objective-C / Cocoa的问题(保留或不...)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过阅读SDK中的内存管理文档,我收集了工厂方法(静态构造函数方法)通常会保留对象并将其添加到自动释放池中。

From reading the memory management docs in the SDK, I gathered that factory methods (static constructor methods) would typically be retaining the object for me and adding it to the autorelease pool?

这意味着我不需要保留&释放一个对象,只要池没有得到释放之前我预期? (应该在应用程序的末尾,对于main()中的默认自动释放池)

This would mean I have no need to retain & release an object as long as the pool does not get released before I expect? (Which should be at the end of the app, for the default autorelease pool in main()? )

这个问题: Cocoa Touch问题。

This question: Cocoa Touch Question. Should [NSMutableArray array] be retained? seems to agree with this.

然而,当我使用NSMutableArray arrayWithCapacity:方法时,我发现我已经使用了NSMutableArray数组。

However when I have used the NSMutableArray arrayWithCapacity: method, I've found I have to retain the array or all heck breaks loose.

我相信这只是总n00b-ness,或者代码中其他地方的一个奇怪的错误,但如果有人

I'm sure this is all just total n00b-ness, or a bizarre bug elsewhere in the code, but if someone could explain how exactly I may have misunderstood, I'd be much obliged.

谢谢!

更新:感谢您的答案。

推荐答案


从读取内存管理docs在SDK中,我收集工厂方法(静态构造函数方法)通常会保留对象并将其添加到autorelease池?

From reading the memory management docs in the SDK, I gathered that factory methods (static constructor methods) would typically be retaining the object for me and adding it to the autorelease pool?

是的,您不必担心从任何方法返回的释放对象,除了 alloc init new copy 方法。

Yes, you don't have to worry about releasing objects returned from any method, except the alloc, init, new, and copy methods.


这意味着我不需要保留&释放一个对象,只要池没有得到释放之前我预期?

This would mean I have no need to retain & release an object as long as the pool does not get released before I expect?

是的。


在应用程序的末尾,对于main()中的默认自动释放池)。

(Which should be at the end of the app, for the default autorelease pool in main()? )

否。你只能依赖于正在使用的对象,直到你从任何方法或函数返回。通常,当控制返回到你的运行循环时,自动释放池被刷新。

No. You can only count on the object being around until you return from whichever method or function you're in. Typically, autorelease pools are flushed when control returns back to your run loop.

如果你想让一个对象实例超过当前方法生存,你必须通过调用'retain'来取得它的所有权。

If you want an object instance to survive beyond the current method you must take ownership of it, by calling 'retain'. You are then also responsible for 'releasing' the instance when you no longer need it.

在你的情况下,如果你想让你的NSMutableArray坚持下去,你需要 retain 它。更好的是,使用 [[NSMutableArray alloc] initWithCapacity:];

In your case, if you want your NSMutableArray to stick around, you need to retain it. Better yet, use [[NSMutableArray alloc] initWithCapacity: ];

请参阅实用内存管理

这篇关于关于工厂方法对象生命周期在Objective-C / Cocoa的问题(保留或不...)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆