NSUserDefault and Switches

大城市里の小女人 提交于 2019-12-24 03:16:35

问题


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];


来源:https://stackoverflow.com/questions/14483338/nsuserdefault-and-switches

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!