Old McStopher
Old McStopher

Reputation: 6349

Sending messages to released objects?

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

Answers (4)

zaph
zaph

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

StilesCrisis
StilesCrisis

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

Mark Adams
Mark Adams

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

user973985
user973985

Reputation: 291

Because they are probably retained before...

Upvotes: 0

Related Questions