确保函数仅在主线程上运行 [英] Make sure function runs on main thread only

查看:126
本文介绍了确保函数仅在主线程上运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何确保我的功能仅在主线程上运行? (它更新UI元素)

这样的函数被认为是坏吗?

How can I make sure that my function is run only on the main thread? (It updates UI elements)
Is a function like this considered 'bad'?

-(void)updateSomethingOnMainThread {
if ( ![[NSThread currentThread] isEqual:[NSThread mainThread]] )
    [self performSelectorOnMainThread:_cmd withObject:nil waitUntilDone:NO];
else {
    // Do stuff on main thread
}
}

我是这样写的,以避免有第二个功能,最初我有这样的:

I wrote it like this to avoid having a second function, initially I had it like this:

-(void)updateSomethingOnMainThread_real {
    // Do stuff on main thread
}

-(void)updateSomethingOnMainThread {
    [self performSelectorOnMainThread:@selector(updateSomethingOnMainThread_real) withObject:nil waitUntilDone:NO];
}


推荐答案

这很好。您也可以使用GCD在主线程上执行代码。

This is fine. You can also use GCD to execute code on the main thread.

查看此SO帖子。

GCD在主线程中执行任务

这篇关于确保函数仅在主线程上运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆