我如何通过
-(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];
,但这是一个非常糟糕的方法,因为我必须重新声明变量,它只是坏。
如何在延迟后传递带有对象的方法?
答案 0 :(得分: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。
答案 1 :(得分:7)
如果要使用 performSelector: 将多个参数传递给方法,请将所有参数保留在NSArray
或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
}
答案 2 :(得分:0)
您可以使用的另一种方法是将NSArray
或NSMutableArray
作为参数传递给您的方法。
一个例子:
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];
该方法可以这样使用:
- (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
}
}
答案 3 :(得分:-1)
根据documentation。对于您的情况,您可以使用NSObject的另一种方法。即
- (id)performSelector:(SEL)aSelector withObject:(id)object1 withObject:(id)object2;
但不幸的是,在这种方法中,你不能给出延迟。