objective c - iOS - Accessing variable declared in method A from method B in the same class -
objective c - iOS - Accessing variable declared in method A from method B in the same class -
how do this? see code illustration below:
- (void)methoda { ... uilabel *label1 = [[uilabel alloc] initwithframe:frame]; ... } - (void)methodb { label1.text = "label 1"; } edit: why i'm wondering because can not set instance variable class. because not know when class loads how many uilabels need. different amount each time class loaded. need dynamically create these uilabels in method , able access these labels throughout rest of class in convenient way.
sounds might want examine design, it's not going easy keeping track of labels need dynamically create. since thats current utilize case, perhaps want maintain mutable array of labels. way can create many need , still able share info across methods (as ivar in class). class definition have (code stolen @macmade , updated):
@interface myclass: nsobject { nsmutablearray * _labels; } @property (nonatomic, retain) nsmutablearray * labels; - ( void )methoda; - ( void )methodb; @end in methoda, create new labels , add together them array. in methodb locate label , set text property.
@implementation myclass @synthesize labels = _labels; - ( id ) init { if( ( self = [ super init ] ) ) { [self setlabels: [nsmutablearray arraywithcapacity: 8]; } } - ( void ) dealloc { [ self.labels release ]; [ super dealloc ]; } - ( void ) methoda { uilabel *label = [[uilabel alloc] initwithframe:frame]; [self.labels addobject: label]; } - ( void ) methodb { // need locate label work with. 1 way index, rough illustration below uilabel * thelabel = (uilabel * ) [self.labels objectatindex: 0]; thelabel.text = @"label 1"; } @end you need way of identifying label dealing -index not best. ideally utilize nsmutabledictionary , store labels keyed name.
hope helps.
objective-c methods
Comments
Post a Comment