Bidirectional, Manual Binding in custom control
Bidirectional, Manual Binding in custom control
- Subject: Bidirectional, Manual Binding in custom control
- From: Jerry Krinock <email@hidden>
- Date: Mon, 21 May 2012 20:44:18 -0700
I modified a "Star Rating" control to be bindings compatible by adding this…
+ (void)initialize {
[self exposeBinding:@"rating"] ;
}
and then binding to it in the window controller's -awakeFromNib like this…
// beForgiving is to handle NSNoSelectionMarker & friends…
NSDictionary* beForgiving ;
NSNumber* no = [NSNumber numberWithBool:NO] ;
NSString* key = NSRaisesForNotApplicableKeysBindingOption
beForgiving = [NSDictionary dictionaryWithObject:no
forKey:key] ;
[starRatingView bind:@"rating"
toObject:fooController
withKeyPath:@"selection.rating"
options:beForgiving] ;
fooController is an NSObjectController. (This is an Inspector window.)
This resulted in a one-way binding; the star rating field lights up according to the 'rating' of the Foo object being inspected in the data model.
In order to make the reverse binding work, that is, in order for the user's clicks on stars update the data model, I needed to add stuff to setRating: in my star rating control like this…
-(void)setRating:(float)rating
{
// Stuff to make reverse binding work…
NSDictionary* bindingsInfo = [self infoForBinding:@"rating"] ;
id object = [bindingsInfo objectForKey:NSObservedObjectKey] ;
NSString* bindingsPath = [bindingsInfo objectForKey:NSObservedKeyPathKey] ;
[object setValue:[NSNumber numberWithFloat:rating]
forKeyPath:bindingsPath] ;
// Set ivar, needsDisplay
…
}
This all makes sense, and it works. But it seems awkward. Is there a better design pattern?
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden