开发者

Bindings AND target/action?

I currently have a color well which keep开发者_如何学运维s track of a color that gets saved in the NSUserDefaults. It is bound to an NSUserDefaultsController. However, I also want to listen for changes to the color so I can update my views accordingly. Therefore, in addition to the binding, I added a target/action to the color well to my preferences controller that posts a notification with the color.

1) How safe is having both target/action and bindings? Is there a possibility that one might lag or they may be out of sync and report different values?

2) When I am getting the color in my IBAction method, should I get it from the user defaults or from the color well?

Here is my colorChanged: action:

- (IBAction)colorChanged:(id)sender
{
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:[colorWell color] forKey:@"color"];
[notificationCenter postNotificationName:@"ColorChangedNotification" object:self userInfo:userInfo];
}

So should I be doing this:

[NSKeyedUnarchiver unarchiveObjectWithData:[[NSUserDefaults standardUserDefaults] objectForKey:@"color"]];

or:

[colorWell color];

Thanks!


1) How safe is having both target/action and bindings? Is there a possibility that one might lag or they may be out of sync and report different values?

I think for the most part, it should be OK. The best way to tell is to test it out.

2) When I am getting the color in my IBAction method, should I get it from the user defaults or from the color well?

You should definitely, definitely get it directly from the color well. Why? There could be a lag when saving to the user defaults. Heck, the defaults could even save only once right before the application terminates, and it would still be alright. (OK, this isn't entirely true, but still) The defaults' main purpose is to persist data in between application launches, not during the lifespan of the app.


It is safe to have both target/action and bindings. If you post notifications with an NSNotificationCenter, then the notifications are delivered synchronously to the observers. (With the obvious caveat that it is not magic--if observer A sends a message to observer B when it gets the notification, observer B will not have received the notification yet. Multiple threads add further complexity.) This is called out in the documentation for NSNotificationCenter.

Reading the color directly from the color well is fast, and probably fine from an IBAction. If you're running code when the application is starting it is best to read from the user defaults because the color well's bindings might not have been updated yet.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜