从块内更新标签的安全方法?
示例:我有这个块,我想更新屏幕上的标签:
[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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
作为比使用
-performSelectorOnMainThread:
更优雅的解决方案,您可以简单地使用一个块来保证 UI 更新在主线程上:请注意,
[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: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.如果您引用了标签,则可以使用 执行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.