user1115269
user1115269

Reputation: 3

Confused with object-c memory management

Below is a code snippet from a book. Why can serialNumber still be set to new value after [serialNumber release];?

 - (void)setSerialNumber:(NSString *)newSerialNumber
{
NSString *newValue;
// Is it a mutable string?
if ([newSerialNumber isKindOfClass:[NSMutableString class]])
// I need to copy it
newValue = [newSerialNumber copy];
else
// It is sufficient to retain it
newValue = [newSerialNumber retain];
[serialNumber release];
serialNumber = newValue;
}

Upvotes: 0

Views: 72

Answers (2)

Chen Harel
Chen Harel

Reputation: 10052

The release message decrement the retainCount by 1. It's just like calling any other function.
When you assign a pointer variable a new value you are relocating the pointer (not the object you just used in the previous statement) to a different object.

Upvotes: 0

yuji
yuji

Reputation: 16725

newValue and serialNumber are just pointers to Objective-C objects. When you send messages like release or retain, they are sent to the actual objects that the pointers point to.

[serialNumber release] sends the release method to the object that serialNumber points to. Then, serialNumber = newValue assigns the same value as the newValue pointer to serialNumber. At that point, the value of the newValue pointer is a mutable string (either the same value as newSerialNumber or a copy of it), which has been retained, since it was either copied or retained, so everything is peachy.

Upvotes: 2

Related Questions