释放数组时,NSMutableDictionary 中使用的对象的内存会发生什么情况?

发布于 2024-12-06 00:31:52 字数 200 浏览 1 评论 0原文

我很好奇当我使用 [array release] 时使用 [array addObject:object] 推送的对象的内存会发生什么情况

  • addObject 会复制指针吗?
  • 我必须保留这些物品吗?
  • 我是否必须创建一个 for 并释放每个对象然后释放数组?

I'm curious what happens with the memory of the objects that I push with [array addObject:object] when I use [array release]

  • does addObject copy the pointers?
  • do I have to retain the objects ?
  • do I have to make a for and release each object then the array?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(4

一抹苦笑 2024-12-13 00:31:52

当您调用

[array addObject:object] 

array时,会保留object,从而增加其保留计数。

稍后,当向 array 发送消息 dealloc 时,它会对 object 调用 release

为了避免内存泄漏,您可能必须在将对象添加到数组后释放它,例如,

NSObject *object = [[NSObject] alloc] init];
[array addObject:object];
[object release];

请确保您查看了内存管理编程指南 确保您没有过度或不足释放对象

When you call

[array addObject:object] 

array retains object, thereby incrementing its retain count.

Later, when array is sent the message dealloc, it calls release on object.

To avoid memory leaks, you may have to release object after you add it to the array, e.g.

NSObject *object = [[NSObject] alloc] init];
[array addObject:object];
[object release];

Make sure you review the Memory Management Programming Guide to be certain that you are not over or under releasing object.

东京女 2024-12-13 00:31:52

addObject 对您添加的对象执行保留操作。当您释放数组时,它会自动对其保存的所有对象调用release。

addObject does a retain on that object you add. And when you release the array it automatically calls release on all objects it holds.

给不了的爱 2024-12-13 00:31:52

当您执行 [array addObject: object] 时,数组将保留插入到数组中的对象。为了避免内存泄漏,不要忘记释放插入的原始对象,否则插入到数组中的对象的保留计数将为 2 而不是 1:

SomeClassObject *obj = [[SomeClassObject alloc] init];
[array addObject:obj];
[obj release];

因为数组拥有数组内部的对象(保存指向该对象的指针并执行保留,如前所述),当您释放数组时,数组知道释放其中的任何对象。工作已为您完成!

When you do [array addObject: object], the array is retaining the object that is inserted into the array. To avoid memory leaks, don't forget to release the original object that was inserted, or else the object being inserted into the array will have a retain count of 2 instead of 1:

SomeClassObject *obj = [[SomeClassObject alloc] init];
[array addObject:obj];
[obj release];

Since the array owns the objects that are inside of the array (holds a pointer to that object and did a retain as explained previously), when you release the array, the array knows to release any objects that are inside of it. The work is done for you!

陌若浮生 2024-12-13 00:31:52

NSArrays 保留添加的对象,因此您不必自己添加额外的保留,并且可以在完成后释放数组。

NSArrays retain added objects, so you don't have to add extra retains yourself, and can just release the array when done.

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