如果我的应用程序在整个运行时使用它,它应如何处理当前日期?

时间:2017-04-22 09:04:43

标签: ios swift nsdate

我应该在哪里放置一个Date实例,如何处理它以获取当前日期?我应该用日期实例制作一个单身人士吗?我应该在AppDelegate的一个函数中调用此实例,以便在应用程序未使用时更新当前日期吗?

2 个答案:

答案 0 :(得分:1)

“我应该在哪里放置一个Date实例,如何处理它以获取当前日期?” 在您当前的View Controller中已经足够了。只要VC活着就可以了 对Date对象有强烈的引用。

“我应该用日期实例制作单身人士吗?” 不。如果你需要保持相关的日期,你需要开一个计时器(让我们说1分钟 所以它不会太麻烦,这将使日期更新在UI

“我应该在AppDelegate的一个函数中调用此实例,以便在应用程序未使用时更新当前日期吗?” 不,您可以收到通知并由他们知道何时放置或关闭计时器。 见代码

class ViewController: UIViewController{
// label to hold the date
@IBOutlet var dateLabel: UILabel!

// timer to keep it updated
var fetchTimer: Timer!

override func viewDidLoad()
{
    super.viewDidLoad()

    // set date immediately (dont wait for timer)
    viewDidEnterForeground()

    // follow Foreground so when we re-enter, timer will launch again
    NotificationCenter.default.addObserver(self,
                                           selector: #selector(ViewController.viewDidEnterForeground),
                                           name:NSNotification.Name.UIApplicationWillEnterForeground,
                                           object: nil)

    // follow background for invalidating timer
    NotificationCenter.default.addObserver(self,
                                           selector: #selector(ViewController.viewDidEnterBackground),
                                           name:NSNotification.Name.UIApplicationDidEnterBackground,
                                           object: nil)
}
// on each entry - set date and fire timer
func viewDidEnterForeground()
{
    setDate()

    fetchTimer = Timer.scheduledTimer(timeInterval: 60.0,
                                      target: self,
                                      selector: #selector(timerFunc),
                                      userInfo: nil,
                                      repeats: true)
}
func viewDidEnterBackground()
{
    fetchTimer.invalidate()
}
func timerFunc()
{
    setDate()
}
func setDate()
{
    let date = Date()

    let formatter = DateFormatter()
    formatter.dateFormat = "dd.MM.yyyy"

    // "22.04.2017"
    let dateFormatString = formatter.string(from: date)

    DispatchQueue.main.async
    {
        self.dateLabel.text = dateFormatString
    }
}
deinit
{
    NotificationCenter.default.removeObserver(self, name:NSNotification.Name.UIApplicationWillEnterForeground, object: nil)

    NotificationCenter.default.removeObserver(self, name:NSNotification.Name.UIApplicationDidEnterBackground, object: nil)
}
}

答案 1 :(得分:1)

你问题的某些部分真的没有意义:

"我应该在哪里放置一个Date实例,如何处理它以获取当前日期?"

Date实例记录固定的时刻。代码

let date = Date()

将在其被呼叫的时刻记录当前日期,而不是更改。如果您的计划明天仍在运行,那么该日期现在已经过时了#34;。

相反,只要您需要当前日期,就应该使用表达式Date()