I am having problem with understanding one concept of memory managment, because I am new to objective C. For instance lets say I have a class Bar and Foo.
in main function I call:
Foo *foo = [bar getFoo]; //In my bar method I return foo
[foo retain];
[foo callMethod];
[foo release];
I know this is right way to do it. But why do we have to retain it after we get it from another object, does not this mean returning object has retain count 0 ? so we have to reatin it to count 1 to use it? but if it has reatin count 0, how do we know it is still there. We can assume since it is the next line that increment retain count that the object memory wont be realocated, but what if we have multi-threading program?
When an class method returns an object, it will
autoreleaseit so you don’t have to bother; typically:If you are only using
foofor the lifetime of the calling method you don’t need toretainit, as it won’t beautoreleased until next time through the run loop, so your code should actually be:If, however, you want to hold
foofor a while, outside the scope of the calling method, you need toretainit and thenreleaseit sometime later.One more thing; the convention for getter method names is simply “name”, so your setter should be
setFooand your getter would befoo. Keeping to the naming conventions is a good idea as it lets you know what a method does, in say 7 months time, and tools like static analysis understand the conventions.