RealmSwift:libc ++ abi.dylib:以NSException类型的未捕获异常终止

时间:2017-06-30 00:46:45

标签: ios realm

我之前能够保存,但我想保存异步。

用户是一个类/对象。每当我尝试在" .async"中运行它时线程失败并出现错误:

libc++abi.dylib: terminating with uncaught exception of type NSException

在线:

let userObjects = self.realm.objects(User.self)

代码:

  let user = User(dictionary: element as? [String : Any])

                print("entering dispatchqueue realm")
                DispatchQueue(label: "background").async {
                    autoreleasepool {
                        let userObjects = self.realm.objects(User.self)
                        do {
                            try! self.realm.write {
                                self.realm.add(user!, update: true)
                            }
                        }
                        catch {
                            print("error saving to realm")
                            // Handle the error case
                        }

                    }
                }

线程安全吗?

编辑:

我能够通过在异步块中移动let realm = try! Realm()

来使其工作

1 个答案:

答案 0 :(得分:0)

在async()块中移动let realm = try! Realm()

让user = User(字典:元素为?[String:Any])

            print("entering dispatchqueue realm")
            DispatchQueue(label: "background").async {
                **let realm = try! Realm()**
                autoreleasepool {
                    let userObjects = self.realm.objects(User.self)
                    do {
                        try! self.realm.write {
                            self.realm.add(user!, update: true)
                        }
                    }
                    catch {
                        print("error saving to realm")
                        // Handle the error case
                    }

                }
            }