我是Realm的新手。我有数据库Reaml,并显示了从数据库到Tableview的一些数据。
我的代码:
class MyRealmObject: Object {
@objc dynamic var id = 0
@objc dynamic var name = ""
@objc dynamic var favorite = false}
class MyViewController: UIViewController, ... {
let realm = try! Realm()
var objectsResult: Results<MyRealmObject>!
...
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = objectsResult[indexPath.row].name
...
return cell
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
//searching block
...
DispatchQueue.global().async {
autoreleasepool{
let realm = try! Realm()
var newObjectsResult: Results< MyRealmObject>!
newObjectsResult = realm.objects(Objects.self).sorted(byKeyPath: "name", ascending: true).filter("name beginswith[cd] %@", searchText)
objectsResult = newObjectsResult
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
}
在这种情况下,我遇到了这个错误:
2018-09-22 14:42:48.262734+0800 TestApp[1194:338211] *** Terminating app due to uncaught exception 'RLMException', reason: 'Realm accessed from incorrect thread.'
如何使用后台线程到主线程的领域对象来重新加载tableview?
答案 0 :(得分:0)
您需要将实例跨线程传递到主线程。您可以通过使用ThreadSafeReference
对象来实现。 Realm documentation包含一个示例:
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"
}
}
}