iOS - Ensure execution on main thread [duplicate]

≡放荡痞女 提交于 2019-11-26 15:14:52

问题


This question already has an answer here:

  • Check whether or not the current thread is the main thread 11 answers

I want to know how to call my function on the main thread.

How do I make sure my function is called on the main thread?

(this follows a previous question of mine).


回答1:


there any rule I can follow to be sure that my app executes my own code just in the main thread?

Typically you wouldn't need to do anything to ensure this — your list of things is usually enough. Unless you're interacting with some API that happens to spawn a thread and run your code in the background, you'll be running on the main thread.

If you want to be really sure, you can do things like

[self performSelectorOnMainThread:@selector(myMethod:) withObject:anObj waitUntilDone:YES];

to execute a method on the main thread. (There's a GCD equivalent too.)




回答2:


This will do it:

[[NSOperationQueue mainQueue] addOperationWithBlock:^ {

   //Your code goes in here
   NSLog(@"Main Thread Code");

}];

Hope this helps!




回答3:


When you're using iOS >= 4

dispatch_async(dispatch_get_main_queue(), ^{
  //Your main thread code goes in here
  NSLog(@"Im on the main thread");       
});



回答4:


i think this is cool, even tho in general its good form to leave the caller of a method responsible for ensuring its called on the right thread.

if (![[NSThread currentThread] isMainThread]) {
    [self performSelector:_cmd onThread:[NSThread mainThread] withObject:someObject waitUntilDone:NO];
    return;
}


来源:https://stackoverflow.com/questions/11582223/ios-ensure-execution-on-main-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!