Should I release a retained local var?


When I’m reading the “Memory Management” chapter, my understanding is if you retain/copy an object, you need to release it immediately or autoRelease it.

But I was not able to understand one example in the book (Pg 69):

- (void)setSerialNumber:(NSString *)str
[str retain];
[serialNumber release];
serialNumber = str;

In this setter method, the argument var str was retained, but it was never released or marked as autoRelease.

Why don’t we need to release it? What did I miss?

Thanks for any help in advance!!



Objects should NOT be released until you are certain they will no longer be used, otherwise you end up with the problem of premature deallocation.

In the example you provided, remember that the pointer str is not the object itself but a type of variable which holds the address where the objects lives.

In the method setSerialNumber, str points to the object which we make the ivar (instance variable) serialNumber point to. If you were to release str in the setSerialNumber method you run into the chance of destroying the object you intend on using as that object’s ivar. This is why you retain the object at the beginning of the method, to guarantee the object’s existence for the lifetime of that object.