从块内更新标签的安全方法?

时间:2011-03-31 12:10:04

标签: iphone objective-c uikit objective-c-blocks

示例:我有这个块,我想更新屏幕上的标签:

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

我担心这不会很好。线程问题等?建议?

2 个答案:

答案 0 :(得分:4)

作为比使用-performSelectorOnMainThread:更优雅的解决方案,您只需使用一个块来保证您的UI更新在主线程上:

[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];
    });
}];

请注意,[NSOperationQueue currentQueue]将返回主队列(如果您运行上述代码的位置),因此在这种情况下您的回调将已在主队列上运行。

答案 1 :(得分:1)

如果您引用了标签,可以使用performselectoronmainthread方法在主线程上更新它。是的,UI不是线程安全的。