IOS - Enforce the main theme

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

How can I make sure my function is called in the main thread?

(this follows the previous question ).

+63
multithreading ios xcode multitasking
Jul 20 '12 at 15:20
source share
4 answers

Is there any rule that I can follow to make sure that my application only runs my own code in the main thread?

As a rule, you do not need to do anything to ensure this - your list of things is usually sufficient. If you don’t interact with some kind of API that happens to spawn a thread and run your code in the background, you will work in the main thread.

If you want to be sure, you can do something like

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

execute the method in the main thread. (There is also the equivalent of GCD.)

+42
Jul 20 '12 at 15:36
source share

This will be done:

 [[NSOperationQueue mainQueue] addOperationWithBlock:^ { //Your code goes in here NSLog(@"Main Thread Code"); }]; 

Hope this helps!

+149
Jul 20 '12 at 15:38
source share

When you use iOS> = 4

 dispatch_async(dispatch_get_main_queue(), ^{ //Your main thread code goes in here NSLog(@"Im on the main thread"); }); 
+120
Jul 20 '12 at 15:41
source share

I think it's cool, even in general its good form to leave the calling method responsible for ensuring that it is called in the right thread.

 if (![[NSThread currentThread] isMainThread]) { [self performSelector:_cmd onThread:[NSThread mainThread] withObject:someObject waitUntilDone:NO]; return; } 
+10
Mar 07 '13 at 0:44
source share



All Articles