gpt4 book ai didi

ios - Swift 使用 realm.add() 或 realm.create() 将大量数据写入 Realm

转载 作者:行者123 更新时间:2023-11-28 05:52:34 31 4
gpt4 key购买 nike

我需要向 Realm 写入大量数据(例如 200000 输入),我使用 realm.add() 在后台线程中写入数据。但它收到了崩溃消息:

Terminating app due to uncaught exception 'RLMException', reason: 'Realm accessed from incorrect thread.'

let cities = try decoder.decode([City].self, from: dataFromStream)
let dispatchQueue = DispatchQueue(label: "com.example.myApp.bg", qos: .background)
dispatchQueue.async {
let myBackgroundRealm = try! Realm()
myBackgroundRealm.beginWrite()

for city in cities {
myBackgroundRealm.add(city, update: false)
}

try! myBackgroundRealm.commitWrite()
}

所以我改为使用 Realm.create(),它起作用了。但是我仍然不明白 Realm.create() 和 Realm.add() 在写入大数据时有什么区别。

let cities = try decoder.decode([City].self, from: data)
let dispatchQueue = DispatchQueue(label: "com.example.myApp.bg", qos: .background)
dispatchQueue.async {
let myBackgroundRealm = try! Realm()

for city in cities {
try! myBackgroundRealm.write {
myBackgroundRealm.create(City.self, value: city, update: false)
}
}
}

最佳答案

当对 Realm 进行异步写入时,您必须初始化线程安全引用并在后台线程中解析该引用。取自 Realm 的文档 https://realm.io/docs/swift/latest/#passing-instances-across-threads

let person = Person(name: "Jane")
try! realm.write {
realm.add(person)
}
let personRef = ThreadSafeReference(to: person)
DispatchQueue(label: "background").async {
autoreleasepool {
let realm = try! Realm()
guard let person = realm.resolve(personRef) else {
return // person was deleted
}
try! realm.write {
person.name = "Jane Doe"
}
}
}

关于ios - Swift 使用 realm.add() 或 realm.create() 将大量数据写入 Realm ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52377899/

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