iOS 中的内存保留和泄漏

发布于 2024-12-03 16:17:16 字数 319 浏览 0 评论 0原文

这是关于内存泄漏的一般问题。假设您有以下代码:

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

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

发布评论

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

评论(1

这样的小城市 2024-12-10 16:17:16

以下是一些规则:

  • 每当您调用 alloc 时,最终都必须调用 release

  • ,您应该

一个release

,当你向数组添加一个对象时, ,它调用该对象的retain。如果您不释放指向该对象的指针,则会发生泄漏。当您释放数组时,它将对其保存的所有对象调用release,因为它之前调用了retain。

NSObject *object = [[NSObject alloc] init]; 
// object has retain count 1
NSArray *array = [[NSArray arrayWithObjects:object] retain]; 
// array is autoreleased but has a retain, so has retain count 1
// object now has retain count 2
[object release];
// object now has retain count 1
[array release];
// array is now set to autorelease, 
// once that happens, array will be sent dealloc and object will be released

因此没有内存泄漏。

Here are some rules:

  • whenever you call alloc, you must eventually call release

  • for every retain, you should have a release

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.

NSObject *object = [[NSObject alloc] init]; 
// object has retain count 1
NSArray *array = [[NSArray arrayWithObjects:object] retain]; 
// array is autoreleased but has a retain, so has retain count 1
// object now has retain count 2
[object release];
// object now has retain count 1
[array release];
// array is now set to autorelease, 
// once that happens, array will be sent dealloc and object will be released

Hence no memory leaks.

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