-2

I have a method say someMethod(), I always want this method should be executed under main thread. So I wrote this method like this..

-(void)someMethod
{
   if([NSThread mainThread])
   {
       // Do method stuffs
   }

   else
   {
       [self performSelectorOnMainThread:@selector(someMethod) withObject:nil waitUntilDone:YES];
   }
}

Questions:

  • Is it the right approach?
  • If, I call this method by background thread, what will happen?

Thanks

Confused
  • 3,846
  • 7
  • 45
  • 72

3 Answers3

1

The "waitUntilDone:YES" is dangerous, it can lead to a deadlock if you don't watch out. Do you really need to wait until the method is finished? Avoid this if at all possible.

gcd is much more flexible; dispatch_async to the main thread will work even if you have a method will all kinds of parameters, including parameters that are not objects.

And if you want to confirm that the method is called on the main thread, that is if calling it on another thread would be a bug, then you use NSAssert.

gnasher729
  • 51,477
  • 5
  • 75
  • 98
-1

Your example is correct. On iOS everything that has to do with the user interface must be executed on the main thread. If code that changes the user interface is executed on a background thread the behaviour is undefined. If your code does not change the user interface it is safe to be run on a background thread.

Jelly
  • 4,522
  • 6
  • 26
  • 42
-1

No, in your case this method can be called on any thread, and you do method stuff only if it's the main thread. A better approach would be to always call the method on the main thread,

//call to your method like this

dispatch_async(dispatch_get_main_queue(), ^{
    someMethod()
});

Edit: You can also double check in the method itself that you are at the main thread

if([NSThread mainThread])
   {
       // Do method stuffs
   }

   else
   {
       dispatch_async(dispatch_get_main_queue(), ^{
         someMethod()
       });
   }
Witterquick
  • 6,048
  • 3
  • 26
  • 50