views:

2860

answers:

3

A typical call to performSelectorOnMainThread: looks like this:

[target performSelectorOnMainThread:action withObject:foo waitUntilDone:NO];

where "result" is an argument passed to "action". A corresponding action would be:

  • (void)doSomethingWithThing1:(id *)thing1

What is the correct syntax for calling an action that takes > 1 argument? Such as:

  • (void)doSomethingWithThing1:(id *)thing1 andThing2(id *)thing2 andAlsoThing3(id *)thing3

[target performSelectorOnMainThread:action withObject:??? waitUntilDone:NO];

Cheers, Doug

A: 

If you wish to preserve the method signature of the receiver then I think you'll need to look at using NSInvocation which allows you to specify multiple argument values.

You could wrap your call and use a dictionary as a container for your arguments as suggested in another answer but to me this seems like a bit of a code smell.

A better solution along this line would be to create a class that encapsulates the argument values - i.e. a strongly typed approach. So for example instead of passing firstname, surname, you'd pass an instance of a Person class. This is probably a better route to go down because methods with fewer arguments can yield cleaner code - but that's a whole other story.

teabot
+2  A: 

You can do it by putting your args in a dictionary or array and passing that to a special function

- (void)doStuff:(NSString *)arg1 and:(NSString *)arg2 and:(NSString *)arg3 {
...
}

- (void)doStuff:(NSArray *)argArray {
    [self doStuff:[argArray objectAtIndex:0]
              and:[argArray objectAtIndex:1]
              and:[argArray objectAtIndex:2];
}
coneybeare
+1  A: 

In response to a similar question on passing non-objects to a method in performSelectorOnMainThread:, I pointed out Dave Dribin's category on NSObject, which lets you do something like the following:

[[person dd_invokeOnMainThread] doSomethingWithThing1:thing1 andThing2:thing2 andAlsoThing3:thing3];

for performing your multi-argument method on the main thread. I think this is a pretty elegant solution. Behind the scenes, he wraps things in an NSInvocation, invoking that on the main thread.

The Amber framework does something similar to this, as well.

Brad Larson
Sweet. Thanks for this gem Brad.
dugla