微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ios – 如何在进入后台后杀死NSTimer并在应用程序恢复活动后创建新的计时器?

所以我正在使用 Swift构建一个简单的iOS应用程序.我需要在应用程序进入后台后终止我的NSTimer,并在应用程序再次激活后创建一个新的NSTimer.

最初我的解决方案是在主控制器文件中的ViewDidLoad()中创建NSTimer类的计时器.这导致我的应用程序中的错误.

我想我需要通过在AppDelegate.swift中使用applicationDidEnterBackground()来终止计时器.但我不确定如何做到这一点.我应该在AppDelegate.swift或主控制器中创建计时器类吗?我不知道Swift文件如何共享类.

我在网上搜索解决方案,但这些帖子都太旧了,解决方案是用Objective-C编写的.

我绝对是初学者.所以我希望有人可以在Swift中解释它.

这是我的主控制器TodoTableViewController.swift中的代码

import UIKit
import CoreData
class TodoTableViewController: UITableViewController,NSFetchedResultsControllerDelegate {....
...
...
override func viewDidLoad() {
    super.viewDidLoad()
    var fetchRequest = NSFetchRequest(entityName: "Todo")
    let sortDescriptor = NSSortDescriptor(key: "dayleft",ascending: true)
    fetchRequest.sortDescriptors = [sortDescriptor]
    if let managedobjectContext = (UIApplication.sharedApplication().delegate as AppDelegate).managedobjectContext {
        fetchResultController = NSFetchedResultsController(fetchRequest:fetchRequest,managedobjectContext: managedobjectContext,sectionNameKeyPath: nil,cacheName: nil)
        fetchResultController.delegate = self
        var e: NSError?
        var result = fetchResultController.performFetch(&e)
        todos = fetchResultController.fetchedobjects as [Todo]
        if result != true {
        println(e?.localizedDescription)
        } }
    var timer = NSTimer.scheduledTimerWithTimeInterval(10,target: self,selector:"update",userInfo:nil,repeats: true)
}
...
}

如果我要在AppDelegate.swift中使计时器无效,我怎样才能将计时器引用到我在TodoTableViewController.swift中创建的计时器?或许我应该把所有与计时器相关的代码放在AppDelegate.swift中?

更新

我试过使用NSNotificationCenter,这是我的代码.

import UIKit
import CoreData

class TodoTableViewController: UITableViewController,NSFetchedResultsControllerDelegate {
...

var timer = NSTimer.scheduledTimerWithTimeInterval(10,selector:"viewDidLoad",repeats: true)

func update(){
    .....
}

override func viewDidLoad() {
    super.viewDidLoad()
    ...

    let notificationCenter = NSNotificationCenter.defaultCenter()

    notificationCenter.addobserver(self,selector: "didEnterBackground",name: "UIApplicationDidEnterBackgroundNotification",object: UIApplication.sharedApplication())

    notificationCenter.addobserver(self,selector: "didBecomeActive",name: "UIApplicationWillEnterForegroundNotification",object: UIApplication.sharedApplication())   
}


func didEnterBackground() {
    timer.invalidate()
}
func didBecomeActive() {
    var timer = NSTimer.scheduledTimerWithTimeInterval(10,repeats: true)
}

...
}

由于计时器是在didBecomeActive()中声明的,因此在didEnterBackground()中有一个错误:没有名为“timer”的成员.如果我在上面发布的代码中声明了didBecomeActive()之外的计时器,那么在调用中会出现“额外参数’选择器’的错误”.我已经将函数update()解析为选择器.我不知道这个错误来自哪里.

解决方法

更新了您的代码添加了一些注释:
class TodoTableViewController: UITableViewController,NSFetchedResultsControllerDelegate 

   //better to instantiate timer inside viewDidLoad
   var timer: NSTimer!

   func update(){ }

   override func viewDidLoad() {
      super.viewDidLoad()
      startTimer()

      let notificationCenter = NSNotificationCenter.defaultCenter()

      //UIApplicationDidEnterBackgroundNotification & UIApplicationWillEnterForegroundNotification shouldn't be quoted
      notificationCenter.addobserver(self,name: UIApplicationDidEnterBackgroundNotification,object: nil)
      notificationCenter.addobserver(self,name: UIApplicationWillEnterForegroundNotification,object: nil)   
   }

   func didEnterBackground() {
      self.timer.invalidate()
   }

   func didBecomeActive() {
      startTimer()
   }

   func startTimer() {
      self.timer = NSTimer.scheduledTimerWithTimeInterval(10,repeats: true)
   }
}

另请注意,NSTimer强烈保持其目标.所以当关闭viewcontroller时 – 定时器应该是无效的.或者会发生内存泄漏,TodoTableViewController永远不会被破坏.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐