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

Fra*_*ade 39 methods selector ios

我试图在一段时间后调用一个方法.

我知道有一个解决方案:

[self performSelector:@selector(myMethod) withObject:nil afterDelay:delay];
Run Code Online (Sandbox Code Playgroud)

我看到了这个问题文档

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

例如:

- (void) MoveSomethigFrom:(id)from To:(id)to;
Run Code Online (Sandbox Code Playgroud)

我将如何使用延迟调用此方法 performSelector:withObject:afterDelay:

谢谢

Mar*_*ich 112

使用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];
});
Run Code Online (Sandbox Code Playgroud)

编辑2015:对于Swift,我建议使用这个小帮手方法:dispatch_after - swift中的GCD?

  • 或者,或者您可以在容器中放置任意数量的参数,并将其作为`performSelector:withObject:afterDelay`方法的参数发送. (2认同)

Eld*_*kov 7

您还可以使用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
Run Code Online (Sandbox Code Playgroud)


cal*_*kus 6

其他想法:

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];
}
Run Code Online (Sandbox Code Playgroud)

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]];
}
Run Code Online (Sandbox Code Playgroud)