Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Binding Realm

woxtu
July 21, 2016
2k

Binding Realm

woxtu

July 21, 2016
Tweet

Transcript

  1. A Realm Object class Person: Object { dynamic var id

    = 0 dynamic var name = "" override static func primaryKey() -> String? { return "id" } }
  2. Using good old KVO let person = Person() let options:

    NSKeyValueObservingOptions = [.Initial, .New] person.addObserver(self, forKeyPath: "name", options: options, context: nil) override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { } }
  3. Using Bond let person = Person() let bnd_name = Observable<String>(object:

    person, keyPath: "name") bnd_name.observe { name in } bnd_name.bindTo(label.bnd_text)
  4. Extend a Realm Object extension Person { class Bindable {

    let id: Int let bnd_name: Observable<String> init(person: Person) { self.id = person.id self.bnd_name = Observable(object: person, keyPath: "name") } } var bindable: Bindable { return Bindable(person: self) } }
  5. Extend a Realm Object let viewModels = ObservableArray<Person.Bindable>(persons.map { $0.bindable

    }) viewModels.lift().bindTo(tableView) { indexPath, viewModels, tableView in let model = viewModels[indexPath.section][indexPath.row] let cell = tableView.dequeueReusableCellWithIdentifier("person", forIndexPath: indexPath) as! PersonTableViewCell model.bnd_name.bindTo(cell.nameLabel.bnd_text).disposeIn(cell.bnd_bag) return cell }
  6. Realm Collection Notifications let viewModels = ObservableArray<Person.Bindable>([])
 
 realm.objects(Person) .addNotificationBlock

    { [weak self] (changes: RealmCollectionChange) in switch changes { case let .Initial(persons): self?.viewModels.extend(persons.map { $0.bindable }) case let .Update(persons, _, _, _): self?.viewModels.diffInPlace(persons.map { $0.bindable }) case let .Error(error): … }