简体   繁体   中英

iVar property, access via self?

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)

如果你是子类,或让其他人重用你的代码并且他们想要覆盖你的功能,那么accessor-method非常方便。

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 ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM