NSUserDefaults and KVO issues

前端 未结 5 1775
清酒与你
清酒与你 2020-12-03 12:11

I\'m using NSUserDefaults in my app and I would like to be notified when a particular value is changed. For that, I added the following lines in viewDidLoad:



        
相关标签:
5条回答
  • 2020-12-03 12:22

    Though its not well documented, NSUserDefaults do support key-value observing in iOS7.

    0 讨论(0)
  • 2020-12-03 12:25

    As of iOS 11.3 this works and is documented:

    Responding to Defaults Changes

    You can use key-value observing to be notified of any updates to a particular default value.

    0 讨论(0)
  • 2020-12-03 12:29

    I suggest making use of the appropriate notification: NSUserDefaultsDidChangeNotification.

    Search for AppPrefs in the Apple Documentation within Xcode and it'll show an example app which does exactly what you want to do. Just compile and run! It makes use of the NSUserDefaultsDidChangeNotification.

    This is the code being used to register an observer:

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(defaultsChanged:)
                                                 name:NSUserDefaultsDidChangeNotification
                                               object:nil];
    
    0 讨论(0)
  • 2020-12-03 12:40

    Interesting observation:

    [NSUserDefaults standardUserDefaults] seems to be KVO compliant now as I am able to observe and bind to it's values. I'm running 10.7.2, using Xcode 4.2, SDK 10.7, LLVM compiler 3.0 .

    I can't seem to find this new behavior documented anywhere in the release notes.

    0 讨论(0)
  • 2020-12-03 12:41

    NSUserDefaults is not KVO compliant, but NSUserDefaultsController is. So you'd use:

    NSUserDefaultsController *defaultsc = [NSUserDefaultsController sharedUserDefaultsController];
    [defaultsc addObserver:self forKeyPath:@"values.pref_server" 
                   options:NSKeyValueObservingOptionNew 
                   context:NULL];
    
    0 讨论(0)
提交回复
热议问题