每秒钟保存到核心数据

时间:2016-09-27 00:53:05

标签: ios swift core-data

情况如下:

我正在处理想要更新特定可听/可查看项目(如歌曲或视频)的NSManagedObject子类的持续时间属性的应用程序。这些信息非常重要,因此需要尽可能准确

解决方案1将在项目完成播放后更新此项,但如果用户从内存中终止应用程序,那么它们处于前台或后台,则会引入另一个如何处理的问题。

解决方案2(似乎绝对是最简单的解决方案)是通过类似于计时器的每秒更新此单一持续时间属性,其中核心数据逻辑在updateDuration方法中发生:

updateTimer = Timer.every(1.0, {
     self.updateDuration(for: self.itemNeedingUpdate)
})
RunLoop.current.add(updateTimer!, forMode: RunLoopMode.commonModes)

我的问题是"这是一件坏事吗?"所有保存操作都在后台线程上处理,如果项目暂停或停止,则计时器也会停止。因此,只有在实际收听或观看项目时才会触发保存操作。我已经在我的项目中对此进行了测试,并且这种方法似乎没有任何性能问题。然而,它在我脑海里举起一面红旗。我很想听听任何人对这个特定解决方案的任何见解。

2 个答案:

答案 0 :(得分:1)

我不确定我完全理解您的应用正在做什么。但是,为了维持不断变化的用户数据,每秒节省一次?我不会犹豫那样做。

答案 1 :(得分:0)

我只是将您的数据保存在applicationWillTerminate(在您的AppDelegate类中),因为当应用程序即将终止时将调用它,无论它是否在后台。

它也应该适用于您的视频需求。

func applicationWillTerminate(application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.

    saveData()
}

保存每一秒只是对线程的错误使用,这是不必要的。

编辑:

我应该更清楚地知道,当应用程序在后台时,并不总是调用上面的方法。一个简单的解决方案是每次应用程序进入后台时保存您的数据:

func applicationDidEnterBackground(application: UIApplication) {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

    saveData()
}

我在App Store上将此方法用于我自己的iOS应用程序,我没有遇到任何问题。即使每秒保存一次也不会显着影响应用的性能,但这似乎是不必要的。