Should I use properties or direct reference when accessing instance variables internally?

前端 未结 5 522
梦谈多话
梦谈多话 2020-12-01 08:30

Say I have a class like this:

@interface MyAwesomeClass : NSObject
{
@private
    NSString *thing1;
    NSString *thing2;
}
@property (retain) NSString *thin         


        
5条回答
  •  栀梦
    栀梦 (楼主)
    2020-12-01 08:48

    Other things mentioned here are all right on. A few things that the other answers missed are:

    First, always keep in mind the implications of accessors/mutators being virtual (as all Objective-C methods are.) In general, it's been said that one should avoid calling virtual methods in init and dealloc, because you don't know what a subclass will do that could mess you up. For this reason, I generally try to access the iVars directly in init and dealloc, and access them through the accessor/mutators everywhere else. On the other hand, if you don't consistently use the accessors in all other places, subclasses that override them may be impacted.

    Relatedly, atomicity guarantees of properties (i.e. your @properties are declared atomic) can't be maintained for anyone if you're accessing the iVar directly anywhere outside of init & dealloc. If you needed something to be atomic, don't throw away the atomicity by accessing the iVar directly. Similarly, if you don't need those guarantees, declare your property nonatomic (for performance.)

    This also relates to the KVO issue. In init, no one can possibly be observing you yet (legitimately), and in dealloc, any remaining observer has a stale unretained (i.e. bogus) reference. The same reasoning also applies to the atomicity guarantees of properties. (i.e. how would concurrent accesses happen before init returns and accesses that happen during dealloc are inherently errors.)

    If you mix and match direct and accessor/mutator use, you risk running afoul of not only KVO and atomicity, but of subclassers as well.

提交回复
热议问题