chrs
chrs

Reputation: 6106

ReactiveCocoa simple property binding with swift

I'm trying to do some simple model - view model binding with ReactiveCocoa using swift

The Workflow:

My model loads some data (categories in this case) and updates its loadingCategories state. true if loading, false if not

Then in my view model I want it to bind its own loading property to the loadingCategories property in the model

Here's the code. It doesn't work. The only examples I could find out there was using signals for UIControls, and I couldn't figure out how to use those examples for property binding (no controls)

let loading = self.categorySelector.rac_valuesAndChangesForKeyPath("loadingCategories", options: .New, observer: nil)
loading.subscribeNextAs { (l:Bool) -> () in
  self.loading = l;
}

When run I just get an "unrecognized selector sent to instance" error.

Upvotes: 1

Views: 850

Answers (1)

Gomino
Gomino

Reputation: 12345

Your observer parameter cannot be nil, it should be the object sending the signal on property change (self.categorySelector)

let loading = self.categorySelector.rac_valuesForKeyPath("loadingCategories",  observer:self.categorySelector)
loading.subscribeNextAs { 
   [weak self] (l:Bool) -> () in
   if (self != nil){
       self!.loading = l;
   }
}

make sure to not retain the ownership on self in the closure by specifying "unowned" otherwise you will have a retain cycle causing memory leak.

Last but not least make sure your observed property is annoted dynamic:

dynamic var loadingCategories:Bool!

Upvotes: 4

Related Questions