[[NSOperationQueue mainQueue] addOperationWithBlock:^ {
//Your code goes in here
NSLog(@"Main Thread Code");
}];
当您使用的是 iOS >= 4 时
dispatch_async(dispatch_get_main_queue(), ^{
//Your main thread code goes in here
NSLog(@"Im on the main thread");
});
有没有任何规则可以遵循,以确保我的应用程序仅在主线程中执行自己的代码?
通常情况下,您不需要做任何事情来确保这一点——您列出的事项通常已经足够了。除非您正在与某些API交互,该API可能会生成一个线程并在后台运行您的代码,否则您将在主线程上运行。
如果您想确保,请尝试进行如下操作:
[self performSelectorOnMainThread:@selector(myMethod:) withObject:anObj waitUntilDone:YES];
在主线程上执行一个方法。(也有一个GCD等效的方式。)
我认为这很酷,尽管通常最好让方法的调用者负责确保在正确的线程上调用它。
if (![[NSThread currentThread] isMainThread]) {
[self performSelector:_cmd onThread:[NSThread mainThread] withObject:someObject waitUntilDone:NO];
return;
}
[NSObject performSelectorOnMainThread]
调用您的委托方法的类才能被视为“安全”。否则,如果对象只是调用[NSObject performSelector]
,则您的委托方法将在调用者线程的上下文中运行。 - trojanfoe