This works, but a bit anti-pattern. I would make a mistake if the thread called by the method is not the main thread. The responder must make sure that the methods are invoked on the correct threads, these types of hacks only encourage ugly code. In addition, if you rely on this, suddenly you double the overhead of sending messages each time you call this method.
If you really cannot change the callerβs behavior, you can try the following:
-(void)methodToBeRunOnMainThreadWithObj:(id)object { dispatch_sync(dispatch_get_main_queue(), ^{
this will cause all the code inside the sending block to be executed in the main thread, and the method will not return until it is completed. If you want the method to return immediately, you can use dispatch_async . If you use dispatch_sync , you can use this trick even in those methods that have non-empty return types.
This code also has the added benefit of supporting methods with non-object arguments ( int , etc.). It also supports methods with an arbitrary number of arguments, while performSelector:withObject: and its sibling methods only support a limited number of arguments. An alternative is to create NSInvocation objects, and that is a pain.
Please note that this requires the Grand Central Dispatch (GCD) on your platform.
yfrancis
source share