exotue
exotue

Reputation: 110

Using 'self' in Swift 2, Xcode 7.0.1

I am making a timer just under the class opening braces (before viewDidLoad) to use as a variable for the entire class. However, when I try to set the timer's target to 'self' I get the error:

Argument type 'NSObject -> () -> ViewController' does not conform to expected type 'AnyObject'

Here is the code for the timer:

class ViewController: UIViewController { 

     var timer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: "update", userInfo: nil, repeats: true)

Upvotes: 0

Views: 390

Answers (1)

Dharmesh Kheni
Dharmesh Kheni

Reputation: 71854

Declare your timer just under the class opening braces (before viewDidLoad) this way:

var timer: NSTimer?

Now in your viewDidLoad method add this code:

timer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: "update", userInfo: nil, repeats: true)

And you can access it anywhere into your class.

Upvotes: 2

Related Questions