objective c - Setting default values for inherited property without using accessor -
i see people debating whether or not use property's setter in -init
method. problem how create default value in subclass inherited property. have class called nslawyer
-- framework class, can't change -- interface looks this:
@interface nslawyer : nsobject { @private nsuinteger _numberofclients; } @property (nonatomic, assign) nsuinteger numberofclients; @end
and implementation looks this:
@implementation nslawyer - (instancetype)init { self = [super init]; if (self) { _numberofclients = 0; } return self; } @end
now let's want extend nslawyer
. subclass called seniorpartner
. , since senior partner should have lots of clients, when seniorpartner
gets initialized, don't want instance start 0
; want have 10
. here's seniorpartner.m:
@implementation seniorpartner - (instancetype)init { self = [super init]; if (self) { // attempting set ivar directly result in compiler saying, // "instance variable _numberofclients private." // _numberofclients = 10; <- can't this. // thus, way set mutator: self.numberofclients = 10; // or: [self setnumberofclients:10]; } return self; } @end
so what's objective-c newcomer do? well, mean, there's 1 thing can do, , that's set property. unless there's i'm missing. ideas, suggestions, tips, or tricks?
you should has have; call accessor. declaring class typically avoids calling own accessors in init
avoid accidentally calling overridden accessor in subclass might rely on consistency of data haven't initialized yet. superclass on other hand should consistent time subclass's init
run, there no problem using superclass accessors @ time.
consider common , general case: want set transform
in uiview
subclass. how solve other call settransform:
? subclassing non-apple code no different.
Comments
Post a Comment