保留/释放返回的对象 [英] Retain/release of returned objects
问题描述
我是 Objective-C 的新手,所以这可能是一个愚蠢的问题.
I am new to Objective-C, so this might be a dumb question.
我不禁看到 ObjC 和 Microsoft 的 COM 在内存管理方面的相似之处(AddRef
/Release
vs retain
/发布代码>).在 COM 环境中,您或多或少需要在将对象返回给调用者之前始终
AddRef
(retain
).从我到目前为止所看到的(我是第三个通过 Cocoa® Programming for Mac® OS X (3rd Edition)),内存管理部分有点模糊.
I cannot help but see the similarities between ObjC and Microsoft's COM with respect to memory management (AddRef
/Release
vs retain
/release
). In a COM environment, it's more or less imposed on you to always AddRef
(retain
) an object before returning it to the caller. From what I've seen so far (I'm a third through Cocoa® Programming for Mac® OS X (3rd Edition)), the memory management part is somewhat fuzzy.
假设没有 GC,返回对象的惯用方式是什么?
Assuming there is no GC, what is the idiomatic way to return an object?
推荐答案
阅读 关于自动释放池的内存管理编程指南.
在 Objective-C 中,按照约定,对象应该自动释放(除非返回对象的方法的名称以alloc"、new"、copy"或mutableCopy"开头).自动释放的对象由池中的 Objective-C 跟踪并自动处理,这意味着您无需关心向它们发送最终版本.与 COM 相比,这极大地简化了引用计数,这就是为什么大多数时候您看不到任何对返回对象的 release
调用.相反,相同的约定指定名称以 alloc、new、copy 或 mutableCopy 开头的方法返回的所有对象都是方法调用者的责任.您必须对这些对象手动调用 release ,否则您的程序将出现内存泄漏.
In Objective-C, by convention, objects should be returned autoreleased (unless the method returning the object has a name that begins with "alloc", "new", "copy", or "mutableCopy"). Autoreleased objects are tracked by Objective-C in a pool and automatically handled, which means you don't need to care about sending a final release to them. This greatly simplifies reference counting compared to COM, and this is why you're not seeing any release
calls on returned objects most of the time. In contrast, the same convention specifies that all objects returned by a method whose name begins with alloc, new, copy, or mutableCopy, are the responsibility of the method caller. You have to manually call release on these objects or your program will have memory leaks.
这篇关于保留/释放返回的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!