Detect changes on NSUserDefaults

后端 未结 5 2107
你的背包
你的背包 2020-12-29 23:45

I\'m developing an iOS application with latest SDK.

I want to know when a property on NSUserDefaults changes it value.

I have found this, but it

5条回答
  •  臣服心动
    2020-12-30 00:35

    try out the NSUserDefaultsDidChangeNotification with this code snippet:

    - (id)init {
    
      self = [super init];
    
      if(self) {
         [[NSNotificationCenter defaultCenter] addObserver:self
                                                  selector:@selector(defaultsChanged:)
                                                      name:NSUserDefaultsDidChangeNotification
                                                    object:nil];
      }
      return self;    
    }
    
    - (void)defaultsChanged:(NSNotification *)notification {
      // Get the user defaults
      NSUserDefaults *defaults = (NSUserDefaults *)[notification object];
    
      NSLog(@"%@", [defaults objectForKey:@"yourIntrestedObject"]);
    }
    
    - (void)dealloc {
     [[NSNotificationCenter defaultCenter] removeObserver:self];
    }
    

提交回复
热议问题