SKAction Perform Selector syntax error

2019-09-04 17:18发布

问题:

Using a SKAction sequence I am trying to add a delay and then call a method with two parameters, however I keep getting the following (new to obj c so could be something simple):

// code 
SKAction *fireAction = [SKAction sequence:@[[SKAction waitForDuration:1.5 withRange:0],
                                [SKAction performSelector:@selector(addExplosion:firstBody.node.position  andTheName: @"whiteExplosion") onTarget:self]]];

// error

Expected ':'

Method declaration

-(void) addExplosion : (CGPoint) position andTheName :(NSString *) explosionName{

When I substitute a method call without parameters seems to work fine.

Any input appreciated.

回答1:

Use [SKAction runBlock:^{}] instead of a selector.

I would use selectors if the method has no parameters. Using a block is much more powerful. But beware of how to use them as it may keep expected deleted objects alive.

__weak typeof(self) weakself = self;
SKAction *fireAction = [SKAction sequence:@[
                        [SKAction waitForDuration:1.5 withRange:0],
                        [SKAction runBlock:^{
    [weakself addExplosion:position andTheName:explosionName];
}]]];

Or use the completion block:

__weak typeof(self) weakself = self;
SKAction *fireAction = [SKAction waitForDuration:1.5 withRange:0];

[someNode runAction:fireAction completion:^{
    [weakself addExplosion:position andTheName:explosionName];
}];


回答2:

The correct syntax for @selector is:

 @selector(addExplosion:andTheName:)

You have to omit the actual variable names, just the parameter names should be specified.

Also allow me to suggest that "andTheName" is a bad parameter name, ObjC guidelines specifically state not to use "and". You lose nothing in readability if your selector parameters would be named like one of these two:

 @selector(addExplosion:name:)
 @selector(addExplosion:withName:)