开发者

Safe way to update a label from inside a block?

Example: I have this block, and I want to update a label on the screen:

[self.motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue currentQueue] withHandler:^(CMDeviceMotion开发者_如何学C *deviceMotion, NSError *error) {
        CMAcceleration *userAcceleration = deviceMotion.userAcceleration;
        self.labelX.text = [NSNumber numberWithFormat:@"%f", userAcceleration.x];
     }];

I fear this won't work well. Threading-problems, etc? Suggestions?


As a more elegant solution than using -performSelectorOnMainThread:, you could simply use a block to guarantee your UI update is on the main thread:

[self.motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue currentQueue] withHandler:^(CMDeviceMotion *deviceMotion, NSError *error) {
    CMAcceleration *userAcceleration = deviceMotion.userAcceleration;

    dispatch_async(dispatch_get_main_queue(), ^{
        self.labelX.text = [NSString stringWithFormat:@"%f", userAcceleration.x];
    });
}];

Note that [NSOperationQueue currentQueue] will return the main queue if that's where you run the above code from, so your callback will already be running on the main queue in that case.


If you have reference to the label you can use performselectoronmainthread method to update it on the main thread. Yes the UI is not thread safe.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜