Question

I'm trying to set the text of a UILabel from within a code block:

PLSRootViewController * __weak weakSelf = self;

[self.analytics.client setMessageHandler:^(MQTTMessage *message) {

    NSArray *beacons = [NSJSONSerialization JSONObjectWithData:message.payload options:NSJSONReadingAllowFragments error:nil];

    weakSelf.streamingCountLabel.text = [NSString stringWithFormat:@"%i", [beacons count]];
}];

But it does not behave as I would expect it and the text does not change even though, if I log to NSLog it actually logs what I would expect.

I could not find the cause of it, but I tried the following:

PLSRootViewController * __weak weakSelf = self;
dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, (int64_t) (NSEC_PER_SEC * 0.0));

[self.analytics.client setMessageHandler:^(MQTTMessage *message) {

    NSArray *beacons = [NSJSONSerialization JSONObjectWithData:message.payload options:NSJSONReadingAllowFragments error:nil];

    NSLog(@"Message: %@", beacons);

    //weakSelf.streamingCountLabel.text = [NSString stringWithFormat:@"%i", ];


    dispatch_after(delay, dispatch_get_main_queue(), ^(void){
        // do work in the UI thread here

        weakSelf.streamingCountLabel.text = [NSString stringWithFormat:@"%i", [beacons count]];

    });
}];

And it actually works now, but I have no clue why. The same happens if I try to change the label's layer background colour, nothing happens, but after a while I can see it flickering and changing.

Could anyone point out what it is that is happening and how could i avoid such situations?

Was it helpful?

Solution

As pointed out by @MidhunMP, the UI should always be updated from the main thread. The reason that it works in your second example is because you're dispatching the UI update on the main thread with dispatch_get_main_queue().

Updating from a non-main thread can have very unpredictable results, with anything from a crash, to an un-updated UI, to breaking your UI.

OTHER TIPS

This code don't work if streamingCountLabel == nil or if you call block in not main thread. Can you check it ?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top