NSUserDefaults之registerDefaults

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

    NSString *stringValue = [userDefaults objectForKey:@"Key"];

        NSLog(@"stringValue = %@",stringValue);

    在这里stringValue的值为nil,一般地我们都是通过 isEqualToString来判断当前的值是否满足条件,也可以更严格的判断是否为nil来确定@"Key"是否注册.

    BOOL boolValue = [userDefaults objectForKey:@"Key"];

    NSLog(@"boolValue = %i",boolValue);

    在bool下当没有注册@"Key"时得到的为NO,这样是有风险的.所以当判断value前还需要判断key的registerDefault.

    - (void)registerDefaults:(NSDictionary<NSString *, id> *)registrationDictionary;

    API给到的注释为

    /*!

     -registerDefaults: adds the registrationDictionary to the last item in every search list. This means that after NSUserDefaults has looked for a value in every other valid location, it will look in registered defaults, making them useful as a "fallback" value. Registered defaults are never stored between runs of an application, and are visible only to the application that registers them.

     

     Default values from Defaults Configuration Files will automatically be registered.

     */

    从上面的解释可以知道使用该方法时,会在UserDefault中查找已经注册的Key,如果存在当前的Key则返回不再注册.

    下面举一个例子:在didFinishLaunchingWithOptions中

    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];

    [userDefaults registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:@"register",@"Test", nil]];

    NSLog(@"userID = %@",[userDefaults objectForKey:@"Test"]);

    在VC的viewDidLoad中

    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];

    [user setBool:YES forKey:@"Test"];

    1.第一次运行demo时会得到 userID = "register".

    2.第二次运行demo时会得到 userID = 1.

    这说明在第二次执行demo时候,registerDefaults:方法并没有修改 a "fallback" value.

posted @ 2018-06-01 14:43  象棋中的象棋  阅读(192)  评论(0编辑  收藏  举报