2016-04-06 6 views

答えて

1

オブジェクトの種類全体を観察する場合は、クエリを作成し、フィルタを適用してNotificationsResultsを観察します。

単一のオブジェクトの変更を観察したい場合は、そのオブジェクトを取得してから、興味のあるプロパティをKey-Value Observation (KVO)で観察できます。

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]!)") 
     } 
    } 
} 
関連する問題