SivaDotRender SivaDotRender -4 years ago 96
Objective-C Question

Label taking a really long time to change

I'm learning to develop an IOS app. I'm having the following problem. I want to use a label to display a string. It takes a really long time for this string to be displayed (10-15 sec). Is this normal? The following code is inside the viewDidLoad function

NSLog(self.example); //displays almost immediately
_labelOutput.text= [NSString stringWithFormat:@"%@", self.example;//takes 15 seconds


The entire viewDidLoad function:

- (void)viewDidLoad
{
[super viewDidLoad];
double lat = 43.7000;
double lon = -79.4000;
NSArray *users = [[NSArray alloc] initWithObjects:@"user_1",@"user_2",@"user_3", nil];

id prediction = [[Prediction alloc] initWithUsers:users Lat:lat Lon:lon];

[prediction populate:^{
self.resName= [prediction generateRandom][@"id"];
NSLog([NSString stringWithFormat:@"%@", self.resName]);
_labelOutput.text= [NSString stringWithFormat:@"%@", self.resName];

}];

}

Answer Source

What does -[Prediction populate:] do with the block? My guess is it runs the block on a background thread or queue. You aren't allowed to modify the UI from a background thread or queue. Your app might crash or just act unpredictably. Your mysterious delay in updating the screen is a common symptom of this mistake.

You must only modify the UI from the main thread or queue. Try this:

[prediction populate:^{
    self.resName= [prediction generateRandom][@"id"];
    NSLog([NSString stringWithFormat:@"%@", self.resName]);
    dispatch_async(dispatch_get_main_queue(), ^{
        _labelOutput.text= [NSString stringWithFormat:@"%@", self.resName];
    });
}];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download