iOS performSelectorOnMainThread with multiple arguments

26,709

Solution 1

When you're using iOS >= 4, you'd do this instead:

dispatch_async(dispatch_get_main_queue(), ^{
    [self doSomething:1 b:2 c:3 d:4 e:5];
});

That's like doing waitUntilDone:NO. If you want to wait until the method is finished, use dispatch_sync instead.

Solution 2

You'll need to use a NSInvocation

Create the object, set the target, selector and arguments.
Then, use

[ invocationObject performSelectorOnMainThread: @selector( invoke ) withObject: nil, waitUntilDone: NO ];

Solution 3

you can pass one object of NSDictionary/NSArray type having required arguments.

and accept the same type of object in your function. then, decompose the values and proceed with processing.

you have to use NSNumber for numeric values for adding them to NSarray/NSDictionary and later on in your function, you can convert them back with intValue/floatValue etc

best of buck.

Share:
26,709
McDermott
Author by

McDermott

Updated on July 09, 2022

Comments

  • McDermott
    McDermott almost 2 years

    I would like to perform a selector on the main thread from another thread, but the selector has multiple arguments, similar to this:

    -(void) doSomethingWith:(int) a b:(float)b c:(float)c d:(float)d e:(float)e { //... }

    How can I get this working with performSelectorOnMainThread: withObject: waitUntilDone:?

    EDIT

    I would like to explain why i need this.

    I'm working with UIImageViews on the main thread, and I make the calculations for them on another thread. I use a lot of calculations so if i make everything on the main thread, the app lags. I know that UI elements can only be manipulated on the main thread, this is why i would like it to work this way, so the main thread can listen to touch events without lags.

  • DarkDust
    DarkDust over 12 years
    That's so NextStep ;-) With GCD this can be solved more easily.
  • Macmade
    Macmade over 12 years
    Sure... But might be handy to know how to do it without GCD, even if GCD is effectively the preferred way now. : )
  • McDermott
    McDermott over 12 years
    I would like to pass an UIImageView too. Can I do that with NSArray?
  • DarkDust
    DarkDust over 12 years
    @McDermott: You can put every object into an NSArray, so yes, you can pass an UIImageView as well.
  • McDermott
    McDermott over 12 years
    Your answer was the best for my problem. It seems that only in a dispatch_sync is a performSelector:afterDelay: working.
  • DarkDust
    DarkDust over 12 years
    You might also want to look into dispatch_after, maybe you can collapse your dispatch_sync and performSelector:afterDelay: into just one call.