I understand that when accessing setter / getter methods for properties I should 开发者_如何学运维be using [self setThisValue:@"a"];
rather than thisValue = @"a";
However with the example below I can see that adding self documents that I am sending a message to an iVar property rather than a locally scoped variable, but does it do anything else in this case?
@interface CustomController : UIViewController {
NSMutableArray *foundList;
}
@property(nonatomic, retain) NSMutableArray *foundList;
@end
.
[[self foundList] addObject:eachObject]; // I usually write this ...
OR
[foundList addObject:eachObject];
gary.
If you have a defined property for an ivar, you should use it rather than accessing the ivar directly. That allows subclasses to override the setter/getter and do something different to just fetching the value from the ivar.
The only exception is in init methods and dealloc.
Using
[[self foundArray] addObject:eachObject];
you just add extra call to the getter method, which is unnecessary in most cases here I think. On the other hand unless you implement your own custom getter and do some weird things there the overhead of this construct is very small so in practice it is just matter of style in my opinion. (I personally would not use property here)
The accessor-method is very convenient if you ever subclass, or have others reusing your code and they want to override your functionality.
using self.ivar also have some issues with memory cleaning. esp. you have retain a property owned by other class. Then you get any new object and wanna change the reference to the self.ivar = newObject. if you do not use self.ivar, it can have bad access, when newObject is also owned by others. The default setter, checks for reference, if not nil, release the old value and set the new ivar to its new value. I was using without an object without self today, and fall into this problem. In short, if the object is shared, use self.ivar ...
精彩评论