Given the next code snippet:
…
- (void) setTotalAmount: (NSNumber*)input
{
[totalAmount autorelease];
totalAmount = [input retain];
}
- (void) dealloc
{
[totalAmount release];
[super dealloc];
}
…
What I want to understand how really we set value.
We allocate local (instance) var and “retain” to input var. But what is “input”? Is it a pointer to real value? Or is it value itself?
When we “retain” do we get a pointer to “input” or pointer to value or just the value?
And pretty same questions with dealloc and release. What actually “dies” here?
Thank you!
It’s clear that
inputis a pointer. You have declared its type in the argument list asNSNumber*.inputis a pointer to an object of typeNSNumber. Internally, the object has an integer variable that holds the number of external references to it. Sending theretainmessage to an object will increment its reference count. Sending thereleasemessage will decrement the count. Sending theautoreleasemessage will adds the object to the local autorelease pool which will keep track of autoreleased objects and sends thereleasemessage to them next time it drains. An object with reference count of 1 that receives areleasemessage will get deallocated and itsdeallocmethod will get called. You should release all the resources you hold when you are deallocated.When you are setting a property, you want to release the old value and make sure the new value is kept around as long as the object itself is alive. To make sure the new value is kept around, you increment its reference count by 1 by sending it the
retainmessage. To release the old object, you’ll send it the release message. There’s one subtle issue here. If the old value is the same as the new value, if you release the old value first and its retain count was 1, it’ll get destroyed before you can increment it. That’s why you should retain the new value before releasing the old one.