Tuesday 15 January 2013

objective c - Is it OK to send messages to self during initialization (and deallocation)? -



objective c - Is it OK to send messages to self during initialization (and deallocation)? -

apple , others recommend against using accessor methods during initialization object may in inconsistent state. general best practice regards sending messages class during initialization? it's quite common, recommended utilize designated initializers. in case have uiview subclass, , subclass has uilabel subview, standard practice?

-(instancetype)init { if(self = [super init]) { _label = [[uilabel alloc] initwithframe:self.bounds]; [self addsubview:_label]; } }

another mutual approach have "convenience" method initializing object. method called initializers (e.g. init, initwithframe:...):

-(instancetype)init { if(self = [super init]) { [self setupview]; } } -(void)setupview { _label = [[uilabel alloc] initwithframe:self.bounds]; [self addsubview:_label]; }

or would, in case, adding subviews view improve suited in different method? override layoutsubviews perhaps?

there's no problem in doing this:

-(instancetype)init { if(self = [super init]) { _label = [[uilabel alloc] initwithframe:self.bounds]; [self addsubview:_label]; } }

after run [super init] line, runtime has created , initialized object. it's safe phone call self afterwards.

regarding lastly question:

adding subviews right in init loads them @ same time instantiate view. they're ready utilize everywhere else in class. adding subviews somewhere else (like in layoutsubviews) lazy-loading: subviews loaded when necessary, must careful not reference them before they're available.

objective-c

No comments:

Post a Comment