带有多个参数的 iOS performSelectorOnMainThread
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8326465/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
iOS performSelectorOnMainThread with multiple arguments
提问by McDermott
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 {
//...
}
-(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:
?
我怎样才能让它工作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.
我在主线程上使用 UIImageViews,并在另一个线程上为它们进行计算。我使用了很多计算,所以如果我在主线程上做所有事情,应用程序就会滞后。我知道 UI 元素只能在主线程上操作,这就是为什么我希望它以这种方式工作,因此主线程可以无延迟地侦听触摸事件。
回答by DarkDust
When you're using iOS >= 4, you'd do this instead:
当您使用 iOS >= 4 时,您应该这样做:
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.
这就像做waitUntilDone:NO
. 如果要等到方法完成,请dispatch_sync
改用。
回答by Macmade
You'll need to use a NSInvocation
您需要使用NSInvocation
Create the object, set the target, selector and arguments.
Then, use
创建对象,设置目标、选择器和参数。
然后,使用
[ invocationObject performSelectorOnMainThread: @selector( invoke ) withObject: nil, waitUntilDone: NO ];
回答by Saurabh Passolia
you can pass one object of NSDictionary/NSArray type having required arguments.
您可以传递一个具有必需参数的 NSDictionary/NSArray 类型的对象。
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
您必须将 NSNumber 用于数值以将它们添加到 NSarray/NSDictionary 以及稍后在您的函数中,您可以使用intValue
/floatValue
等将它们转换回来
best of buck.
最好的降压。