Reputation: 6349
I have several UIView subclasses (buttons, labels, etc.) that follow the following setup pattern. My question is, why are messages still able to be sent to the UILabel
after release
?
myLabel = [[UILabel alloc] initWithFrame:someFrame];
[someUIView addSubview:myLabel];
[myLabel release];
myLabel.textAlignment = UITextAlignmentCenter;
// other property changes to myLabel
They are "owned" by a new UIView, I suppose, but I don't understand why release
doesn't destroy the original object and thereby all messages to it. I'm not making property changes through someUIView
's subViews
. I'm not complaining. I'm just trying to understand why.
EDIT: I should add that these are instance variables, if that makes a difference.
Upvotes: 1
Views: 97
Reputation: 112857
The object is not destroyed as long as the retain count is greater than 0. In this case someUIView
has retained the object.
It is really best not to access an object after releasing it. a better pattern might be:
myLabel = [[[UILabel alloc] initWithFrame:someFrame] autorelease];
myLabel.textAlignment = UITextAlignmentCenter;
[someUIView addSubview:myLabel];
myLabel = nil;
Second example:
myLabel = [[UILabel alloc] initWithFrame:someFrame];
[someUIView addSubview:myLabel];
myLabel.textAlignment = UITextAlignmentCenter;
// other property changes to myLabel
[myLabel release];
myLabel = nil;
Upvotes: 3
Reputation: 16290
Your call to -addSubview:
calls -retain
on the label when it receives it. At this point, you relinquish ownership (by calling -release
) and only the view owns it. But it still exists until the containing view also releases it.
Upvotes: 1
Reputation: 30846
You can still send messages to the label because the label hasn't been released yet. -addSubview:
retains the objects passed in, so the object remains in memory since the view is still holding a reference and you didn't nil the myLabel
pointer.
Upvotes: 0