Why Release first?


#1

A question -
Chapter 20 / Page 132 / 2nd code fragment on the page.

In the example, the code goes:

[color=#408000]- (void)setHolder:(Employee *)newEmp
{
[newEmp retain];
[holder release];
holder = newEmp;
}[/color]

My question is, why Release ‘holder’ before ‘holder=newEmp’ ?
----- I understand ‘holder’ points (or may) to address of Old employee object.
----- Since Old and New employee are the same ‘type’, wouldn’t just ‘overwriting’ old address with new address work the same?
--------------Or just use the code fragment ‘holder = newEmp;’…without… adding the code ‘[holder release]’ before it ??

Help, please…

.


#2

Well, to send the message release to an object, you need to have its address. Until the assignment, that address is stored in holder. If you do the assignment before the release, you’d need to hold the address somewhere:

- (void)setHolder:(Employee *)newEmp { [newEmp retain]; Employee *oldEmployee = holder; holder = newEmp; [oldEmployee release]; }

Which would work fine, but is more code And doesn’t get you anything.

In this case, it is really important to keep the difference between the variable (which holds the pointer) and the object it points to.


#3

…I was going to ask, why even release?

But I guess Holder needs to relinquish ownership of the old Employee object (in cases of strong reference)
and/or
reduce good old Retain count?

ps: Thank you, for taking time reply especially on a Sunday.


#4

You have it exactly right: to relinquish ownership of the Employee object that it had been owning.


#5

Phew. I wasn’t sure.

I appreciate your time.