I have a few basic questions regarding the syntax and usage of properties in Objective C:
Assume the following declaration in the header:
@interface TestObject : NSObject {
NSArray *myArray;
}
@property (nonatomic, retain) NSArray *myArray;
In the implementation, can I:
- List item
- Use
myArrayandself.myArrayinterchangeably for setting and getting purposes? - Is
self.myArray = nilequivalent to[myArray release]?
If so, Is there ever a reason to useself.myArray = nilrather than[myArray release]?
myArrayandself.myArrayare actually different.myArrayis accessing the variable directly, whereasself.myArray(which is equivalent to[self myArray]) is calling an accessor method. Most people agree that you should useself.myArray(or[self myArray]) all the time, and never usemyArraydirectly. This is because the accessor might have side effects; for example, KVO won’t work if you set your variable directly, and memory management won’t be handled for you.Your property is declared with
retain, soself.myArray = anArray(which is the same as[self setMyArray:anArray]) does the following:Therefore, when you do
self.myArray = nil, one of the steps (#2) is indeed release the old array. (And since the new one isnil, we don’t have to worry about its memory management, even though we retained it.) So yes,self.myArray = nilis a valid way of releasingmyArray.HOWEVER, if you’re talking about releasing
myArrayindealloc, it’s generally a good idea to use[myArray release], because callingself.myArray = nilwill have side effects if any other objects are observingmyArraythrough KVO. So while it does follow memory management standards, it’s not a good idea to write yourdeallocmethod usingself.myArray = nil.