I have a UI that was made using code only pretty much: everything (UIlabels, etc) are initialized within viewdidload of the view controller.
.h
@interface homeViewController : UIViewController {
//IBOutlet UILabel *lbl; // not using an outlet anyway...
UILabel *lbl;
}
@property(nonatomic,retain) UILabel *lbl;
@end
.m
@interface homeViewController ()
@end
@implementation homeViewController
@synthesize lbl;
-(void)updateLabel {
NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
double temptemp2 = [ud doubleForKey:@"somekey"];
lbl.text = [NSString stringWithFormat:@"%f", temptemp2];
[ud synchronize];
}
then in the viewdidload i just call [self updateLabel]; and the label does not get updated. however, if I put the same code that’s inside updateLabel method into view did load, the code works.
the UIlabel is being initialized (alloc init) ahead of the [self updateLabel]; inside of view did load .
How should I initialize the label object properly if I do not want to do it using interface builder? so that it is accessible form other methods inside of the same view controller?
You have created a @property on your view controller for the label, however when you create the label you are assigning it to a local variable instead of the property. Because of this you are unable to reference it later from your other method when you want to assign the value.
In your
viewDidLoad, assign the UILabel object you have created to the property like this:Then in your
updateLabelmethod: