0

我怎样才能通过

-(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]; 但这是一种非常糟糕的方法,因为我必须重新声明变量,这很糟糕。

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

4

4 回答 4

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

其中 aPoint 和 sprite 在您的块之外定义。

于 2013-05-24T09:00:47.447 回答
7

如果您想使用performSelector:将多个参数传递给方法,请将所有参数保留在NSArrayor中NSDictionary,然后传递该数组/字典,如

  [self performSelector:@selector(testWith:) withObject:array afterDelay:3];  

编辑

  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
 }
于 2013-05-24T09:07:17.170 回答
0

Another aproach you can use is to pass an NSArray or an NSMutableArray as parameter to your method. An Example:

NSString *firstItem = @"first Item";
NSNumber *secondItem = [[NSNumber numberWithBool:YES];
YourCustomObject *thirdItem= [[YourCustomObject alloc] init];

//your array to pass
NSArray *arrayToPass = [[NSArray arrayWithObjects:firstItem, secondItem, thirdItem, nil];

//call you method after delay and pass all the objects:
[self oerformSelector:@selector(doStuffWithMultipleParams:) withObject:arrayToPass afterDelay:3.0f];

The method could be used like this:

 - (void)doStuffWithMultipleParams:(NSArray *)passedArray{
    String *s; 
    BOOL b;
    YourCustomObject *obj;
    if ([[passedArray objectAtIndex:0] isKindOfClass:[NSString class]]){
        s = [passedArray objectAtIndex:0];
    }
    if ([[passedArray objectAtIndex:1] isKindOfClass:[NSNumber class]]){
        b = [[passedArray objectAtIndex:1] boolValue];
    }
    if ([[passedArray objectAtIndex:1] isKindOfClass:[YourCustomObject class]]){
        obj = [passedArray objectAtIndex:2];
    }
    if (s || b || obj){
        //now do stuff with these objects
    }


}
于 2013-05-24T09:11:38.067 回答
-1

根据文档。对于您的情况,您可以使用 NSObject 的另一种方法。IE

- (id)performSelector:(SEL)aSelector withObject:(id)object1 withObject:(id)object2;

但不幸的是,在这种方法中你不能给延迟。

于 2013-05-24T09:01:01.257 回答