iOS 中的内存保留和泄漏
这是关于内存泄漏的一般问题。假设您有以下代码:
NSObject *object = [[NSObject alloc] init];
NSArray *array = [[NSArray arrayWithObjects:object] retain];
[object release];
[array release];
这是内存泄漏吗?比如,在释放整个数组之前,我是否必须枚举数组中的所有对象并一一释放它们?或者 NSArray 的 dealloc 方法是否释放其中的所有对象以及释放数组本身?
感谢您的帮助!内存管理可能非常棘手。
This is a general question about memory leaks. Let's say you have the following code:
NSObject *object = [[NSObject alloc] init];
NSArray *array = [[NSArray arrayWithObjects:object] retain];
[object release];
[array release];
Is that a memory leak? Like, would I have to enumerate through all the objects in the array and release them one by one before releasing the entire array? Or does NSArray's dealloc method release all of the objects within it as well as releasing the array itself?
Thanks for any help! Memory management can be quite tricky.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
以下是一些规则:
每当您调用
alloc
时,最终都必须调用release
,您应该
一个
release
,当你向数组添加一个对象时, ,它调用该对象的retain。如果您不释放指向该对象的指针,则会发生泄漏。当您释放数组时,它将对其保存的所有对象调用release,因为它之前调用了retain。
因此没有内存泄漏。
Here are some rules:
whenever you call
alloc
, you must eventually callrelease
for every
retain
, you should have arelease
When you add an object to an array, it calls retain on that object. If you don't release your pointer to that object, it will be a leak. When you release the array, it will call release on all of the objects that it holds, since it called retain previously.
Hence no memory leaks.