NSUserDefaults removeObjectForKey vs. setObject:nil

后端 未结 3 939
时光说笑
时光说笑 2021-01-30 19:26

Are the following two lines equivalent?

1. [[NSUserDefaults standardUserDefaults] removeObjectForKey:@\"example key\"]

2. [[NSUserDefa

3条回答
  •  感动是毒
    2021-01-30 20:00

    Yes, both lines of code are equivalent, both will result in nil read

    id obj = [[NSUserDefaults standardUserDefaults] objectForKey:@"example key"];
    

    NSUserDefaults will return nil if the key was not found. I would recommend to use the removeObjectForKey instead of setting it to nil.

    here is how to test if setting key value to nil removed the key entry from NSUserDefaults standardUserDefaults.

    NSArray *keys = [[[NSUserDefaults standardUserDefaults] dictionaryRepresentation] allKeys] copy];
       for(NSString *key in keys) {
           NSLog(@"Key Name: %@", key);
    }
    [keys release];
    

    or simply dump the key/value dictionary of NSUserDefaults standardUserDefaults

    NSLog(@"All contents of NSUserDefaults: %@", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);
    

提交回复
热议问题