如何调用延迟多个参数的方法

我试图延迟一段时间后调用一个方法。

我知道有一个解决scheme:

[self performSelector:@selector(myMethod) withObject:nil afterDelay:delay]; 

我看到了这个问题和文档

但我的问题是:我怎样才能调用一个方法,需要两个参数?

例如:

 - (void) MoveSomethigFrom:(id)from To:(id)to; 

我怎么会延迟调用这个方法,使用performSelector:withObject:afterDelay:

谢谢

使用dispatch_after:

 double delayInSeconds = 2.0; dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC); dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ //code to be executed on the main queue after delay [self MoveSomethingFrom:from To:to]; }); 

编辑2015年:对于斯威夫特,我build议使用这个小帮手方法: dispatch_after – 快速GCD?

您也可以使用NSInvocation对象在NSObject的类别中实现方法(适用于所有版本的iOS)。 我想这应该是这样的:

 @interface NSObject(DelayedPerform) - (void)performSelector:(SEL)aSelector withObject:(id)argument0 withObject:(id)argument1 afterDelay:(NSTimeInterval)delay { NSMethodSignature *signature = [self methodSignatureForSelector:aSelector]; NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature]; [invocation setTarget:self]; [invocation setSelector:aSelector]; [invocation setArgument:&argument0 atIndex:2]; [invocation setArgument:&argument1 atIndex:3]; [invocation performSelector:@selector(invoke) withObject:nil afterDelay:delay]; } @end 

其他想法:

1)你可以使用NSInvocations:

+ (NSInvocation *)invocationWithMethodSignature:(NSMethodSignature *)signature
(>>参见Eldar Markov的答案 )

文档:
https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSInvocation_Class/Reference/Reference.html

2)你可以使用一个辅助方法..

 [self performSelector:@selector(helperMethod) withObject:nil afterDelay:delay]; - (void) helperMethod { // of course x1 and x2 have to be safed somewhere else [object moveSomethigFrom: x1 to: x2]; } 

3)你可以使用数组或字典作为参数。

 NSArray* array = [NSArray arrayWithObjects: x1, x2, nil]; [self performSelector:@selector(handleArray:) withObject:array afterDelay:delay]; - (void) handleArray: (NSArray*) array { [object moveSomethigFrom: [array objectAtIndex: 0] to: [array objectAtIndex: 1]]; } 

迅速:

  let delayInSeconds = 3.0; let delay = delayInSeconds * Double(NSEC_PER_SEC) let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delay)); dispatch_after(popTime, dispatch_get_main_queue(), { // DO SOMETHING AFTER 3 sec }); 

下面是如何在Swift中延迟一段时间后触发一个块:

 runThisAfterDelay(seconds: 5) { () -> () in print("Prints this 5 seconds later in main queue") //Or perform your selector here } /// EZSwiftExtensions func runThisAfterDelay(seconds seconds: Double, after: () -> ()) { let time = dispatch_time(DISPATCH_TIME_NOW, Int64(seconds * Double(NSEC_PER_SEC))) dispatch_after(time, dispatch_get_main_queue(), after) } 

参数计数并不重要。

它包含在我的回购标准function: https : //github.com/goktugyil/EZSwiftExtensions

这些都可以工作,但都比需要的复杂得多。

使用NSDictionary参数devise要调用的方法。 把它的对象,你需要的。

如果您希望方法也可以通过其他方式访问,请调用一个方法来“解开”字典,并使用显式参数调用预期的方法。