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

发布于 2024-10-28 02:39:18 字数 394 浏览 1 评论 0原文

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

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

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

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

[self.motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue currentQueue] withHandler:^(CMDeviceMotion *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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

娜些时光,永不杰束 2024-11-04 02:39:18

作为比使用 -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] 将返回如果主队列是您运行上述代码的位置,那么在这种情况下您的回调将已经在主队列上运行。

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.

独自←快乐 2024-11-04 02:39:18

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文