Blog‎ > ‎

Some Tricky Codes to Bind UISwitch with NSUserDefaults Settings

posted May 25, 2011, 7:56 PM by Leo - www.superarts.org -
Since iOS does not have NSDefaults binding (official document: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CocoaBindings/Concepts/NSUserDefaultsController.html), if we want it we have to write some codes ourselves. Of course, there should be tons of ways of doing this, and I'll share some codes which in my opinion are quite interesting.

First, in an NSString category, write something like this for codes like [@"setting-enabled" setting_set_switch:my_switch]:


546 //  setting + ui
547 
548 - (void)setting_set_switch:(UISwitch*)a_switch
549 {
550     a_switch.on = [self setting_bool];
551 }
552 
553 - (void)setting_get_switch:(UISwitch*)a_switch
554 {
555     [self setting_bool:a_switch.on];
556 }

Then in an NSObject category, these codes are for "fake instance variables" (got the idea from here: http://oleb.net/blog/2011/05/faking-ivars-in-objc-categories-with-associative-references/):


 48 #pragma mark associate
 49 
 50 - (void)associate:(NSString*)key with:(id)obj
 51 {
 52     objc_setAssociatedObject(self, key, obj, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
 53 }
 54 
 55 - (id)associated:(NSString*)key
 56 {
 57     return objc_getAssociatedObject(self, key);
 58 }

Finally, add our own UISwitch Category:


 39 #pragma mark LYSwitch
 40 
 41 @interface UISwitch (LYSwitch)
 42 - (void)bind_setting:(NSString*)key;
 43 @end
 44 
 45 @implementation UISwitch (LYSwitch)
 46 - (void)bind_setting:(NSString*)key
 47 {
 48     [key setting_set_switch:self];
 49     [self associate:@"ly-setting-name" with:key];
 50     [self addTarget:self action:@selector(value_changed) forControlEvents:UIControlEventValueChanged];
 51 }
 52 - (void)value_changed
 53 {
 54     [[self associated:@"ly-setting-name"] setting_bool:self.on];
 55 }
 56 @end

How to use:


In the init routine, simply set binding info:

 17     [switch_setting_shuffle bind_setting:@"setting-player-shuffle"];
 18     [switch_setting_repeat bind_setting:@"setting-player-repeat"];

So the settings are binded with the UISwitches:

623 - (IBAction)action_setting_changed
624 {
625     NSLog(@"setting shuffle: %i", switch_setting_shuffle.on);
626     NSLog(@"setting repeat: %i", switch_setting_repeat.on);
627 }

To be continued: you can use code like this to bind all the UIControls. Quite funny codes, huh?
Comments