Search code examples
iphoneobjective-cmemory-managementretainautorelease

Objective C, Memory Management


1) What is the reason for the use of retain?

For example, in a setter method:

- (void) setCount: (int) input {
    [intCount autorelease];
    intCount = [input retain];
}

2) the autorelease-Method: Is it deleting an old object or preparing the new one?

3) Why the retain-method is called at the input-object?

Would

intCount = input;

be wrong? And why?


Solution

    1. Retain is used to increment the retainCount of an object. NSObjects have a property called retainCount which maintains a count on the number of references that are currently held on an object. When the retainCount of an object reaches 0, the object can be released from memory. Effectively this prevents an object from being released from memory if it's still in use elsewhere.

    2. The autorelease method does not delete an old object and does not prepare the new object. It is effectively a pre-emptive call to release the object (autorelease is much more complicated than that and you should read up on it in the Memory Management Guide.)

    3. In your case intCount = input wouldn't be wrong because you're working with a primative. However if input were an object then you'd need to be calling retain on it. In fact you don't even need to be writing your own getters/setters for primatives (or objects), but instead should be using Declared Properties. In fact you're almost always better off using Declared Properties and if you do want to roll your own, get to know the pitfalls of doing so first.