How can I pass
-(void)explosionFromPoint:(CGPoint)explosionPoint withSprite:(CCSprite*)sprite;
in a
[self performSelector:@selector(//Right here) withObject:nil afterDelay:3];
?
You cant put the whole selector inside the @selector()
, and withObject
first of all only allows one object to be passed over, and neither do I understand how to use it.
How can I pass a method with objects after a delay?
I also tried a workaround where I call
[self performSelector:@selector(waitExplosion) withObject:nil afterDelay:3];
which then runs the action itself, [self explosionFromPoint:c0TileCoord withSprite:bomb];
, but this is a really bad way to do it as I have to re-declare the variables and it's just bad.
How can I pass a method with objects after a delay?
You could use 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];
});
Where aPoint and sprite are defined outside of your block.
If you want to pass multiple arguments to a method using performSelector: , keep all the arguments in a NSArray
or NSDictionary
and then pass that array/dictionary like
[self performSelector:@selector(testWith:) withObject:array afterDelay:3];
Edit
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
}
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
}
}
As per the documentation. For your case you can make use of another method of NSObject. ie
- (id)performSelector:(SEL)aSelector withObject:(id)object1 withObject:(id)object2;
But unfortunately in this method you can not give the delay.