A beginner's question: I am trying to remove a subview after having added it to a view and then releasing it, i.e. I have:
for (int i = 0; i < 9, i++) {
UIButton *btn = [indexButtons objectAtIndex:i];
btn.tag = x;
[notePage1 addSubview:btn];
[btn release];
}
How can I get rid of one of these btn, e.g. number 0? I thought of
UIBu开发者_StackOverflow中文版tton *btn = [indexButtons objectAtIndex:0];
if ([btn isDescendantOfView:notePage1]) { [btn removeFromSuperview]; }
[btn release];
But this will simply crash the app. I get no error log at all? - app simply terminates. How do I do this properly?
You shouldn't release the button, because you didn't allocate it.
It's all about object ownership. You should never release an object that you don't own. You can take ownership of an object by sending one of the following messages:
- alloc
- new
- retain
- copy
You shouldn't release the button in any of these snippets. You only use release
if you have specifically used retain
, alloc
, copy
or new
.
Your code should be:
for (int i = 0; i < 9, i++) {
UIButton *btn = [indexButtons objectAtIndex:i];
btn.tag = x;
[notePage1 addSubview:btn];
}
and
UIButton *btn = [indexButtons objectAtIndex:0];
if ([btn isDescendantOfView:notePage1]) { [btn removeFromSuperview]; }
Adding to a to a superview increases the retain count automatically and removing releases automatically. You don't have to worry about any of it.
don't release buttons, you never Alloc'ed them
精彩评论