更具体地说,我有一个函数(incomeToday),它是将数字相加,然后当日期改变时,我想将当天的收入加到总和中,再除以一个数字(自开始以来的天数-该部分正在工作),这样我就可以看到平均收入pr。日期:
func IncomeToday () -> Double {
let IncomeInput = Double(IncomeTextField.text!)
todayIncome = todayIncome + IncomeInput!
return todayIncome
func TotalIncome ()
let averageIncome = (totalIncome + IncomeToday())/ Days
averageIncome.text = "\(averageIncome)"因此,当日期发生变化(在00:00)时,我希望运行函数TotalIncome()。这是可能的吗?如果是的话,是如何实现的?(我正在用NSDate()想象一些东西,但完全不确定是如何实现的)。
非常感谢!
发布于 2016-09-22 17:29:10
这个函数每天被调用一次。只有当日期改变时,才会调用它。在appdelegate中调用此函数。
let defaults = NSUserDefaults.standardUserDefaults()
let date = NSDate()
let frmt = NSDateFormatter()
frmt.dateFormat = "YYYY-MM-dd"
let today = frmt.stringFromDate(date)
if let savedDate = defaults.objectForKey("today")
{
if self.compareTwoDates(savedDate as! String, secondDate: today) == false {
// perform calculations
// this block gets called if the date is changed
}
} else {
// perform calculations
// this block gets called for the first time only.
}
self.defaults.setValue(today, forKey: "today")
// here we save the today's date for next day's comparison日期比较函数为
func compareTwoDates(firstDate: String, secondDate: String) -> Bool {
let frmt = NSDateFormatter()
frmt.dateFormat = "YYYY-MM-dd"
let date_first = frmt.dateFromString(firstDate)
let date_second = frmt.dateFromString(secondDate)
return (date_first?.isEqualToDate(date_second!))!
}https://stackoverflow.com/questions/39583335
复制相似问题