Wednesday, August 15, 2018

Utility functions for ios NSUserDefault

1. Dump all items in NSUserDefault


NSArray *keys = [[[NSUserDefaults standardUserDefaults] dictionaryRepresentation] allKeys];

for(NSString* key in keys){
        NSLog(@"%@ : %@",key, [[NSUserDefaults standardUserDefaults] valueForKey:key]);
}



2. Observe changes in NSUserDefault


- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
  [[NSUserDefaults standardUserDefaults] addObserver:self
                                            forKeyPath:@"mykey"
                                               options:NSKeyValueObservingOptionNew
                                               context:NULL];

    self.viewController = [[MainViewController alloc] init];
    return [super application:application didFinishLaunchingWithOptions:launchOptions];
}

- (void)observeValueForKeyPath:(NSString *) keyPath ofObject:(id) object change:(NSDictionary *) change context:(void *) context
{
    if([keyPath isEqual:@"mykey"])
    {
       NSLog(@"SomeKey change: %@", change);
    }
}

3. Settings bundle with NSUserDefault
Application can use ios Settings app to allow user to configure settings. However, settings put into Settings.bundle root.plist will not be automatically picked up when app reads settings from NSUserDefault. The settings only apply to NSUserDefault after user change the value from settings app.
So if user has not change a setting from ios setting app, read the key from nsuserdefault will return nil, which means the key does not exist in NSUserDefault.
One way to overcome this issue is calling NSUserDefault regsiterDefault method, this will set the initial values in NSUserDefault for all the keys in NSDictionary parameter. 

No comments:

Post a Comment