How do I call performSelectorOnMainThread: with an selector that takes > 1 arguments?

烈酒焚心 提交于 2019-12-31 08:13:08

问题


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];

回答1:


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.




回答2:


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];
}



回答3:


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.



来源:https://stackoverflow.com/questions/1460589/how-do-i-call-performselectoronmainthread-with-an-selector-that-takes-1-argum

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!