一个初学者的问题:我试图在将子视图添加到视图然后释放它之后删除子视图,即我有:
for (int i = 0; i < 9, i++) {
UIButton *btn = [indexButtons objectAtIndex:i];
btn.tag = x;
[notePage1 addSubview:btn];
[btn release];
}
如何摆脱其中一个btn,例如: 0号?我想到了
UIButton *btn = [indexButtons objectAtIndex:0];
if ([btn isDescendantOfView:notePage1]) { [btn removeFromSuperview]; }
[btn release];
但这只会让应用程序崩溃。我什么都没有错误日志? - 应用程序只是终止。我该怎么做呢?
答案 0 :(得分:3)
你不应该释放按钮,因为你没有分配它。
关于对象所有权。您永远不应该释放您不拥有的对象。您可以通过发送以下消息之一来获取对象的所有权:
答案 1 :(得分:1)
不要释放按钮,你永远不会Alloc'ed他们
答案 2 :(得分:1)
您不应该在任何这些片段中释放按钮。如果您专门使用release
,retain
,alloc
或copy
,则只能使用new
。
您的代码应为:
for (int i = 0; i < 9, i++) {
UIButton *btn = [indexButtons objectAtIndex:i];
btn.tag = x;
[notePage1 addSubview:btn];
}
和
UIButton *btn = [indexButtons objectAtIndex:0];
if ([btn isDescendantOfView:notePage1]) { [btn removeFromSuperview]; }
添加到超级视图会自动增加保留计数并自动删除版本。您不必担心任何问题。