问题
I have a timer that's counting down by 3. I'm triggering the timer in the viewDidLoad method where I'm also querying time variables from Parse.
Here's my code where the timer function is:
var createdAt = object.createdAt
if createdAt != nil {
let calendar = NSCalendar.currentCalendar()
let comps = calendar.components([.Hour, .Minute, .Second], fromDate: createdAt as NSDate!)
let hour = comps.hour * 3600
let minute = comps.minute * 60
let seconds = comps.second
self.timerInt.append(hour + minute + seconds)
var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("countDown"), userInfo: nil, repeats: true)
}
}
}
})
self.tableView.reloadData()
}
I've tried changing around the self.tableView.reloadData()
because I'm assuming that it's a reloadData problem.
Here is my countdown function:
func countDown() {
//timerInt is an array where I'm storing the Int values.
for i in 0 ..< timerInt.count {
let hours = timerInt[i] / 3600
let minsec = timerInt[i] % 3600
let minutes = minsec / 60
let seconds = minsec % 60
print(String(format: "%02d:%02d:%02d", hours, minutes, seconds))
timerInt[i]--
}
self.tableView.reloadData()
}
I want this all to happen in the cellForRowAtIndexPath method..
Here is cellForRowAtIndexPath method:
let hours = timerInt[indexPath.row] / 3600
let minsec = timerInt[indexPath.row] % 3600
let minutes = minsec / 60
let seconds = minsec % 60
//defining the time
myCell.secondLabel.text = String(format: "%02d:%02d:%02d", hours, minutes, seconds)
//formatting the time
return myCell
Any ideas as to what is making it trigger 3x?
回答1:
Stupid of me. Realized that if I'm querying 3 objects from Parse the seconds count down by 3. If I'm querying 4, then the seconds count down by 4.
The problem was where I'm triggering the timer method:
var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("countDown"), userInfo: nil, repeats: true)
I need to trigger it OUTSIDE of where I'm querying. Because if it's triggered there, then it's been triggered with the amount of objects I'm querying.
Now I put the timer
variable like this and it works :) :
var createdAt = object.createdAt
if createdAt != nil {
let calendar = NSCalendar.currentCalendar()
let comps = calendar.components([.Hour, .Minute, .Second], fromDate: createdAt as NSDate!)
let hour = comps.hour * 3600
let minute = comps.minute * 60
let seconds = comps.second
self.timerInt.append(hour + minute + seconds)
}
}
}
var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("countDown"), userInfo: nil, repeats: true)
})
self.tableView.reloadData()
}
Note, the }
are from other closures within my viewDidLoad.
来源:https://stackoverflow.com/questions/33414661/why-is-my-timer-counting-down-by-3-every-second