Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Christian Bjørtomt
3,967 PointsNSTimer "target: self" returns error "Unresolved identifier"
I trying to make a "pet", and want the hunger to decrease every x-minute. But every time I use the NSTimer and say that "target: self" I get an error?
Code snippet:
var hunger = 10
var timer = NSTimer(timeInterval: 10, target: self, selector: Selector(decreaseHunger()), userInfo: nil, repeats: true)
func decreaseHunger(){ hunger -= 1 }
1 Answer
Oliver Duncan
16,642 PointsYou have to be within an object to reference self, which refers to the current instance of that object.
More importantly, I think you have to add a timer to a run loop, something which I honestly couldn't help you with. However, there is a class method that will do what you want - Timer.scheduledTimer. I whipped this up in a playground, worked like a charm:
import UIKit
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
class Pet {
var hunger = 10
var timer: Timer?
init() {
timer = Timer.scheduledTimer(withTimeInterval: 2, repeats: true) { (timer) in
if self.isFull() {
timer.invalidate()
print("Your pet is full!")
} else {
self.hunger -= 1
print(self.hunger)
}
}
}
func isFull() -> Bool {
return self.hunger == 0
}
}
let pet = Pet() // Prints 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, Your pet is full!
Note how you have to make import the PlaygroundSupport framework to make the playground run indefinitely(by default, it'll stop once it reaches the end of your code). Also note this is Swift 3, might be slightly different if you're using Swift 2.