如何在Realm模型上设置观察者?

时间:2016-04-06 14:04:05

标签: swift realm

出于调试目的,我想在模型上设置观察者/观察者,但到目前为止我还没有找到提示。

请注意,我在iOS开发中相当新(不到一个月),所以我可能会遗漏一些东西。

2 个答案:

答案 0 :(得分:1)

如果您想观察整类对象,可以进行查询,应用过滤器,然后针对Notifications观察这些ffcd = -51 in 16-Bit binary complement fe75 = -395 in 16-Bit binary complement 1f68 = 8040 in 16-Bit binary complement

如果您想观察单个对象的更改,可以检索它,然后通过Key-Value Observation (KVO)观察您感兴趣的属性。

答案 1 :(得分:0)

以下是Realm(Swift)中KVO的示例: 仅用于演示KVO i Realm如何使用持久对象。

class MyRealmClass: Object {
    dynamic var id = NSUUID().UUIDString
    dynamic var date: NSDate?
    override static func primaryKey() -> String? {
        return "id"
    } 
}

class ViewController: UIViewController {
    var myObject: MyRealmClass?

    private var myContext = 0

    override func viewDidLoad() {
        super.viewDidLoad()

        myObject = MyRealmClass()
        try! uiRealm.write({ () -> Void in
            myObject?.date = NSDate()
            uiRealm.add(myObject!, update: true)
            print("New MyClass object initialized with date property set to \(myObject!.date!)")
        })

        myObject = uiRealm.objects(MyRealmClass).last
        myObject!.addObserver(self, forKeyPath: "date", options: .New, context: &myContext)

        //Sleep before updating the objects 'date' property.
        NSThread.sleepForTimeInterval(5)

        //Update the property (this will trigger the observeValueForKeyPath(_:object:change:context:) method)
        try! uiRealm.write({ () -> Void in
            myObject!.date = NSDate()
        })
    }

    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        if context == &myContext {
            print("Date property has changed, new value is \(change![NSKeyValueChangeNewKey]!)")
        }
    }
 }