davdroman / Bohr

Settings screen composing framework
MIT License
1.26k stars 83 forks source link

callback when choice is changed #13

Closed mythodeia closed 9 years ago

mythodeia commented 9 years ago

Hello and thanks for this great library. I was wondering if there is a way to know when a user changes a value in an BOChoiceTableViewCell cell. I haven't subclassed the cell so i am using the demo for now. So i want to be able to do something when i user changes his choice in the cell. can you help? thanks

davdroman commented 9 years ago

Hello there @mythodeia!

This is a pretty good question, and it focuses on one of the key points of Bohr: extensibility. Bohr could be even more magical if it handled NSUserDefaults default values itself, or even NSUserDefaults keys by itself, but turns out this would be a huge inconvenience for this kind of observing operation.

What you basically want to do to see if a NSUserDefault value associated with a key changed is observing it like:

[[NSUserDefaults standardUserDefaults] addObserver:self forKeyPath:@"yourKey" options:NSKeyValueObservingOptionNew context:NULL];

and then observe the change in observeValueForKeyPath:ofObject:change:context:.

While this is pretty messy, exposing NSUserDefaults observation to the developer so that they only rely on it when there's an active instance of BOTableViewController is a pretty dangerous thing to do and can easily lead to pretty nasty bugs, so you're better off on your own.

Anyway, if you're using some FRP framework such as ReactiveCocoa you can take advantage of this by neatly observing any NSUserDefault value like this:

[[[NSUserDefaults standardUserDefaults] rac_channelTerminalForKey:@"yourKey"] subscribeNext:^(id yourValue) {
        // Do something with the new value.
}];
mythodeia commented 9 years ago

thanks for the reply. i am using NSUserDefaults now but i wanted something less hacky. Something like a delegate method would be nice. :+1: keep up the good work

davdroman commented 9 years ago

I don't think the observing way is hacky at all. It may seem messy, but it's the recommended way to go by Apple.

May I close this issue?

mythodeia commented 9 years ago

thanks :+1: