NSUserDefault and Switches

2019-07-21 09:05发布

问题:

I use NSUserDefaults to save a switch on/off and so far it is good. It remembers the switch position in next session.

Now to the thing which I do not understand. I use the same switch (with the same name)in another view, let´s say a flip view which is pushed in from the first view. If I change the switch in the first view it is automatically changed in the flip view. But the other way round, if I change it in the flip view it is not changed in the first view when I go back. Only if I restart the application the first view is also changed.

How can I solve this to be changed at the same time? Or kind of refresh the first view without need to restart.

回答1:

Your first view is not refreshed, as it is not initialized again. If you using ViewControllers you could update your switch in viewWillAppear (if isViewLoaded).



回答2:

You should observe NSUserDefaults changes in views that are interested in the changes.

You can use the following code to observe the changes:

NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self
           selector:@selector(defaultsChanged:)  
               name:NSUserDefaultsDidChangeNotification
             object:nil];

And implement the defaultsChanged method:

- (void)defaultsChanged:(NSNotification *)notification
{
    NSUserDefaults *defaults = (NSUserDefaults *)[notification object];
    id value = [defaults objectForKey:@"keyOfDefaultThatChanged"];
    self.something = [(NSNumber *)value intValue];    // For example.
}

Don't forget the remove the observer when your view closes (perhaps in dealloc):

NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center removeObserver:self];