向 NSArray 添加对象会发生泄漏,但为什么呢?

发布于 2024-12-22 16:12:28 字数 377 浏览 2 评论 0原文

我有一个类,其中包含一个名为 _contents 的 NSMutableArray。该数组在创建此类的实例时初始化,并且有一个方法 setContentsObject: 用于将对象添加到内容中。这是 setContentsObject 的实现:

- (void)addContentsObject:(id <MyProtocol>)object
{
    [_contents addObject:object];
}

非常简单,并且有效,但是当我使用 Leaks 工具分析应用程序的运行时,我在该方法的一行上收到了报告的泄漏(标记为“100%”)。我知道 addObject: 保留了该对象,但我以前从未遇到过这个问题,而且我不知道这个方法还可以做些什么。

I have a class which contains an NSMutableArray called _contents. This array is initialised on creation of an instance of this class, and there is a method setContentsObject: to add an object to the contents. This is the implementation of setContentsObject:

- (void)addContentsObject:(id <MyProtocol>)object
{
    [_contents addObject:object];
}

Pretty simple, and it works, but when I analyse the running of my app using the Leaks instrument, I get a reported leak (labeled '100%') on the one line of that method. I understand that addObject: retains the object, but I've never had this issue before and I don't see what more could be done to this method.

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

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

发布评论

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

评论(3

瑾兮 2024-12-29 16:12:28

我遇到过 addObject 泄漏的情况,只需用 insertObject:atIndex 替换该行即可修复它。我什至通过多次泄漏测试来证明这一点。

现在,我可以告诉您泄漏的确切原因以及泄漏时间吗?不是真的……我可以猜测并说后者更准确。我绝对知道它解决了我的问题,只是将其归类为错误:)

I have ran into instances where addObject leaks and simply replacing that line with insertObject:atIndex fixes it. I even proved it by running several leaks tests.

Now, can I give you an exact reason of why it leaks and when? Not really... I can take a guess and say that the latter is more precise. I definitely know it fixed my issue and just classified it as a bug :)

一百个冬季 2024-12-29 16:12:28

如果没有更多代码就无法判断。但是,addObject: 将保留您传递给它的内容。因此,您可以认为数组“拥有”该对象,并且您可以在调用 addContentsObject: 方法后释放它。

正如 Hot Licks 提到的,如果没有人释放该数组,它拥有的所有对象也将挂起。

您可能想要使用 Leaks 工具执行的操作是查看泄漏的对象之一,并查看所有引用。

哦,您可能要考虑切换到 ARC。

Impossible to tell without more code. But, addObject: will retain what you pass it. So you can consider that the array “owns” the object, and you can release it after calling your addContentsObject: method.

And as Hot Licks mentioned, if nobody every releases the array, all the objects it owns will hang around as well.

What you may want to do with the Leaks instrument is look at one of your leaked objects, and see all the references.

Oh, and you may want to consider switching to ARC.

夏有森光若流苏 2024-12-29 16:12:28

我很确定这与 Obj-C 查看方法名称的方式有关。任何以 -copy -add 或 -new 为前缀的内容都会向返回的对象添加保留计数。如果您不希望这样,请尝试重命名该方法一次,看看是否仍然泄漏。我的猜测是不会。

I'm pretty sure it has to do with the way Obj-C looks at method names. Anything prefixed with -copy -add or -new will add a retain count to your returned object. If you don't intend it to be this way, try renaming the method once and see if it still leaks. My guess is it won't.

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