Each object has a reference counter. When it goes to 0, the object is freed.
Assuming the property was declared as @property (retain) :
Your first example, line by line:
- The object is created by
alloc ; it has a reference count of 1. - The object is passed to the
self setAController: method, which sends it a retain message (because the method does not know where the object is coming from), increasing the number of references by 2. - The calling code no longer needs the object itself, so it calls
release , reducing the number of links to 1.
In your second example, steps 1 and 2 are mostly performed, but not 3, so at the end, the object's reference count is 2.
The rule is that if you create an object, you are responsible for releasing it when you are done with it. In your example, the code is executed using tempAController after it sets the property. The responsibility of the setter method is to call retain if it needs this object.
It is important to remember that self.property = foo; in Objective-C is actually just a shorthand for [self setProperty:foo]; and that the setProperty: method will save or copy objects as needed.
If the property was declared @property (copy) , then the object would be copied, not saved. In the first example, the source object will be released immediately; in the second example, the initial counter of references to objects will be equal to 1, although it should be equal to 0. Thus, you still want to write your code in the same way.
If the property was declared @property (assign) , then self does not require ownership of the object, but someone else needs to save it. In this case, the first example will be incorrect. These kinds of properties are rare, and are usually used only for object delegates.
benzado 01 Oct '08 at 4:54 2008-10-01 04:54
source share