Realm Async Thread Swift 3

时间:2017-02-17 22:08:40

标签: swift asynchronous realm

使用Xcode-8.2.1,Swift-3.0.2,RealmSwift-2.2.0,iOS-Simulator-10:

尝试使用Realm-Object编写View-Model,我在另一个线程中创建一个returnArray失败了。问题是对先前创建的realm-object的访问失败(很可能是由于后台线程访问?)。

有人可以告诉我以下代码有什么问题(见下文): 重要提示:在“getEntries-completionHandler”之前调用“createDataEntries() - method”(正确的SimPholders realmobject-entry可以看到)!因此,“类别”设置为“爱”(见代码)

import Foundation
import RealmSwift

class MVVMCBalancesModel: BalancesModel
{

    fileprivate var entries = [BalancesDataEntry]()
    let realm = try! Realm()

    init() {
        self.createDataEntries()
    }

    fileprivate func createDataEntries() {

        let myBalance = BalancesDataEntry()
        myBalance.index = 0
        myBalance.category = "Love"  // !!!!!!! Here the category is filled

        try! self.realm.write {

            self.realm.deleteAll()
            self.realm.add(myBalance)
        }
    }

    func getEntries(_ completionHandler: @escaping (_ entries: [BalancesDataEntry]) -> Void)
    {
        // Simulate Aysnchronous data access
        DispatchQueue.global().async {

            var returnArray: [BalancesDataEntry] = [BalancesDataEntry]()
           let realmy = try! Realm()
            let cnt = realmy.objects(BalancesDataEntry.self).count
            for idx in 0 ..< cnt {
                let obj = realmy.objects(BalancesDataEntry.self).filter("index = \(idx)").first!
                returnArray.append(obj)
            }
            completionHandler(returnArray)  // !!!!!!! BREAKPOINT (see screenshot below)
        }
    }
}

运行上面的代码并在completionHandler(returnArray)上设置断点会产生以下结果:

enter image description here

为什么returnArray的“类别”为空字符串???

1 个答案:

答案 0 :(得分:4)

从底层存储中懒惰地检索从Realm检索的对象的属性。从Swift访问属性将返回适当的值。同样,如果您从Xcode的LLDB控制台运行po returnArray,您应该会看到对象的完整状态。调试器弹出窗口中显示的实例变量仅在对象未受管理时(在添加到Realm之前)使用。