Marcus Handley Marcus Handley - 19 days ago 6
Swift Question

NSInvalidArgument exception when using #selector swift3

When I run the function

func makeSpriteShoot(bullets bulletInfo:MHBulletInformation,player playerSprite:SKSpriteNode){
print("Foo")
let shootTimer = Timer.scheduledTimer(timeInterval: bulletInfo.frequency, target: true, selector: #selector(shootBullet), userInfo: nil, repeats: true)
}
func shootBullet(){
player.shootBullet(angle: 90)//player is a instance of a subclass of SKSpriteNode
}


I get the following exception+SIGABRT:


terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFBoolean shootBullet]: unrecognized selector sent to instance ...


Both of the above functions are inside a subclass of SKScene running in Swift3.

Notably I do not get any compile time error unlike
#selector(test)

Answer

You have made mistake in setting target with Boolean value.

target is the object to which to send the message specified by aSelector when the timer fires. The timer maintains a strong reference to target until it (the timer) is invalidated.

So simply set target to self if method exist in class where you scheduling Timer.

let shootTimer = Timer.scheduledTimer(timeInterval: bulletInfo.frequency, target: self, selector: #selector(shootBullet), userInfo: nil, repeats: true)