Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update a UILabel in Xcode programmatically without XIB files?

I'm stuck :(
In my application I require an update from CLLocationManager every time it gets an update to a new position. I am not using XIB/NIB files, everything I coded I have done programmatically. To the code:
the .h


@interface TestViewController : UIViewController
    UILabel* theLabel;

@property (nonatomic, copy) UILabel* theLabel;

@end

the .m


...

-(void)loadView{
    ....
    UILabel* theLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0,0.0,320.0,20.0)];
    theLabel.text = @"this is some text";

    [self.view addSubView:theLabel];
    [theLabel release]; // even if this gets moved to the dealloc method, it changes nothing...
}

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{
    NSLog(@"Location: %@", [newLocation description]);

    // THIS DOES NOTHING TO CHANGE TEXT FOR ME... HELP??
    [self.view.theLabel setText:[NSString stringWithFormat: @"Your Location is: %@", [newLocation description]]];

    // THIS DOES NOTHING EITHER ?!?!?!?
    self.view.theLabel.text = [NSString stringWithFormat: @"Your Location is: %@", [newLocation description]];

}
...

Any ideas, or help?

(this was all hand jammed so please forgive me if it looks kinda gacked) I can provide more info if needed.

like image 993
dcrawkstar Avatar asked Apr 04 '11 18:04

dcrawkstar


1 Answers

Your loadView method is wrong. You do not set the instance variable properly but instead you generate a new local variable. Change it to the following by omitting the UILabel * and do not release it because you want to keep a reference around to the label to set the text later.

-(void)loadView{
    ....
    theLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0,0.0,320.0,20.0)];
    theLabel.text = @"this is some text";

    [self.view addSubView:theLabel];
}

- (void) dealloc {
    [theLabel release];
    [super dealloc];
}

Then later directly access the variable like this:

 - (void)locationManager:(CLLocationManager *)manager
     didUpdateToLocation:(CLLocation *)newLocation
            fromLocation:(CLLocation *)oldLocation
 {
     NSLog(@"Location: %@", [newLocation description]);

     theLabel.text = [NSString stringWithFormat: @"Your Location is: %@", [newLocation description]];

 }
like image 132
GorillaPatch Avatar answered Sep 18 '22 05:09

GorillaPatch