skytect
skytect

Reputation: 387

Argument of '#selector' does not refer to an '@objc' method, property or initializer

Can anyone tell me why this code gives the error message "Argument of '#selector' does not refer to an '@objc' method, property or initializer"?

timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector:#selector(updateTimer(until: 3)), userInfo: nil, repeats: true)   

Here's the function:

func updateTimer(until endTime: Int) { 
    counter -= 1
    timeLabel.text = String(counter)
    if counter == endTime {
        step += 1
    }
}

What I have tried:
1. Adding @objc in front of the function.

Upvotes: 5

Views: 9857

Answers (1)

vadian
vadian

Reputation: 285059

The selector of a target / action method must be declared either without parameter or with one parameter passing the affected object.

In case of a Timer use the userInfo parameter to pass data.

timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector:#selector(updateTimer(_:)), userInfo: 3, repeats: true)   


func updateTimer(_ timer: Timer) { 
    let endTime = timer.userInfo as! Int
    counter -= 1
    timeLabel.text = String(counter)
    if counter == endTime {
        step += 1
    }
}

If the enclosing class does not inherit form NSObject you have to add the @objc attribute to the action method.

Upvotes: 5

Related Questions