关于发布的目标C(iphone)问题 [英] objective C (iphone) question about releasing

查看:80
本文介绍了关于发布的目标C(iphone)问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我创建一个视图,并将其添加为子视图并将其添加到数组中,是否必须将其释放两次?

If I create a view, and add it as a subview and also add it to an array, do I have to release it twice?

    UIView* cat = [[UIView alloc] initWithFrame:someFrame];
    [self.view addSubview:cat];
    [self.animals addObject:cat];
    [cat release];
    [cat release];

我似乎很奇怪有2条发布声明,而且我还没有看到有人这样做.但是在这种情况下,保留计数不会增加2吗?

It just seems weird to me to have 2 release statements, and I haven't seen people doing that. But doesn't the retain count increase by 2 in this case?

推荐答案

您应该只有一个release —平衡alloc. addSubView:addObject:都不赋予调用者对该对象的所有权,因此调用者不需要用release平衡它们.阅读内存管理指南应该清除所有内容这个给你.

You should only have one release — to balance the alloc. Neither addSubView: nor addObject: give the caller ownership over the object, so the caller does not need to balance them with a release. Reading the memory management guide should clear all this up for you.

记住"NARC"可能会有所帮助-如果您在包含单词" n ew"," a lloc"," r tain"或" c opy",则需要释放它.正如您在上面的代码中看到的那样,只有alloc符合要求.由于只对它进行了一次NARC处理,因此只需释放一次即可.

It might help to remember "NARC" — if you call a method on an object that includes the word "new", "alloc", "retain" or "copy", you need to release it. As you can see in your code above, only alloc fits the bill. Since you only NARCed it once, you only need to release it once.

这篇关于关于发布的目标C(iphone)问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆