gpt4 book ai didi

ios - 在 applicationWillTerminate 中删除 Realm 数据

转载 作者:可可西里 更新时间:2023-11-01 01:19:50 26 4
gpt4 key购买 nike

我有以下情况,当应用程序从设备内存中抛出时,我从 Realm 中删除了非实际数据。我有一个特殊的 FriendRealmManager 类,这个类包含函数 clearCache,它删除用户(目前不是 friend )。当我在applicationWillTerminate函数中调用这个manager时,回到应用程序后,我发现这个函数没有起作用,因为有模型的用户不再是 friend 。我试图将 clearCache 函数的代码移到 applicationWillTerminate 中,这有效。请告诉我,是否可以做类似的事情来处理 applicationWillTerminate 中不同管理器的功能?

普通函数和静态函数我都试过了。

没用

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

class FriendRealmManager {

static func clearCache() {
DispatchQueue.main.async {
do {
let realm = try Realm()
try realm.write {
let nonFriendUsers = realm.objects(RealmUser.self).filter("isFriend == %@ AND isMain == %@", false, false)
realm.delete(nonFriendUsers)
}
} catch {
debugPrint(error.localizedDescription)
}
}
}
}

有效

func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
do {
let realm = try! Realm()
try realm.write {
let nonFriendUsers = realm.objects(RealmUser.self).filter("isFriend == %@ AND isMain == %@", false, false)
realm.delete(nonFriendUsers)
}
} catch {
debugPrint(error.localizedDescription)
}
}

最佳答案

您的函数无法正常工作的最可能原因是您将其作为异步函数调用,并且系统在您的函数执行之前终止了您的应用程序。查看 applicationWillTerminate 的官方文档,它指出

Your implementation of this method has approximately five seconds to perform any tasks and return. If the method does not return before time expires, the system may kill the process altogether.

因此,我建议从您的函数中删除 DispatchQueue.main.async 部分,然后同步运行您的删除操作。

关于ios - 在 applicationWillTerminate 中删除 Realm 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44429892/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com