如何将多个对象传递给延迟方法?

Osc*_*and 0 xcode objective-c cocos2d-iphone ios

我怎么能通过

-(void)explosionFromPoint:(CGPoint)explosionPoint withSprite:(CCSprite*)sprite;

在一个

[self performSelector:@selector(//Right here) withObject:nil afterDelay:3];

你不能把整个选择器放在里面@selector(),withObject首先只允许一个对象被传递,我也不理解如何使用它.

如何在延迟后传递带有对象的方法?我也尝试了一个解决方法,我打电话

[self performSelector:@selector(waitExplosion) withObject:nil afterDelay:3]; 然后运行动作本身,[self explosionFromPoint:c0TileCoord withSprite:bomb]; 但这是一个非常糟糕的方法,因为我必须重新声明变量,它只是坏.

如何在延迟后传递带有对象的方法?

小智 11

你可以使用dispatch_after.

double delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
    [self explosionFromPoint:aPoint withSprite:sprite]; 
});
Run Code Online (Sandbox Code Playgroud)

其中aPoint和sprite是在块之外定义的.

  • 这不是`performSelector:withObject:afterDelay:`的确切替换因为GCD`dispatch_after`不能被取消而`performSelector:withObject:afterDelay:`可以用`cancelPreviousPerformRequestsWithTarget:selector:object:`取消 (3认同)

Ani*_*ese 7

如果要使用performSelector:将多个参数传递给方法,请将所有参数保存在NSArray或中NSDictionary,然后将该数组/字典传递给

  [self performSelector:@selector(testWith:) withObject:array afterDelay:3];  
Run Code Online (Sandbox Code Playgroud)

编辑

  NSArray *array =[NSArray arrayWithObjects:@"arg1",@"arg2"];
 [self performSelector:@selector(testWith:) withObject:array afterDelay:3];


 -(void)testWith:(NSArray *)array
 {

   NSString * arg1 =[array objectAtIndex:0];// first argument
   NSString *arg2 = [array objectAtIndex:1];// second argument
   // do other stuff
 }
Run Code Online (Sandbox Code Playgroud)