0

I have a function working with a button:

@IBAction func btnSiguiente(_ sender: Any) { if indexImagenes == imagenes.count { indexImagenes = 0 } escaparate.image = NSImage(named: imagenes[indexImagenes]) indexImagenes += 1 } 

I want to make it work with a Timer:

 var playTimer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(autoplay), userInfo: nil, repeats: true) func autoplay() { if indexImagenes == imagenes.count { indexImagenes = 0 } escaparate.image = NSImage(named: imagenes[indexImagenes]) indexImagenes += 1 } 

But I get this in console:
[_SwiftValue autoplay]: unrecognized selector sent to instance 0x6080000451c0

2
  • try playTimer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(autoplay), userInfo: nil, repeats: true) Commented Mar 12, 2017 at 1:19
  • When you create the timer, what is self? Commented Mar 12, 2017 at 17:10

1 Answer 1

3

To fix this, initialize the timer once the instance of the class your are in is fully initialized.

So just give the var playTimer a default value as follows:

var playerTimer:Timer? = nil 

Then initialize the timer in some function that gets called once 'self' is fully initialized (like viewDidLoad() for example, assuming this code is in a viewController):

override func viewDidLoad() { super.viewDidLoad() playerTimer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(autoplay), userInfo: nil, repeats: true) } 

Essentially just make sure 'self' is fully initialized before you send it a selector to perform.

Sign up to request clarification or add additional context in comments.

1 Comment

Excellent! Yeah always make sure the object your sending a method call to is fully instantiated.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.