在AppDelegate里写了如下代码:
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; //注册默认设置 NSDictionary *defaultValues = [NSDictionary dictionaryWithObjectsAndKeys:0,@"currency",YES,@"dailyNotification", nil]; [userDefaults registerDefaults:defaultValues]; BOOL flag = [userDefaults boolForKey:@"dailyNotification"];
flag还是为NO。
registerDefaults到底要怎么用?莫非默认值的设置要用set吗?
解决方案
20
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; //注册默认设置 NSDictionary *defaultValues = [NSDictionary dictionaryWithObjectsAndKeys: [[NSNumber alloc] initWithBool:NO], @"currency", [[NSNumber alloc] initWithBool:YES], @"dailyNotification", nil]; [userDefaults registerDefaults:defaultValues]; [userDefaults setValue:[[NSNumber alloc] initWithInt:0] forKey:@"dailyNotification"]; BOOL flag = [userDefaults boolForKey:@"dailyNotification"]; NSLog(@"flag = %d", flag); [userDefaults removeObjectForKey:@"dailyNotification"]; flag = [userDefaults boolForKey:@"dailyNotification"]; NSLog(@"flag = %d", flag);
你的代码:
NSDictionary *defaultValues = [NSDictionary dictionaryWithObjectsAndKeys:0,@"currency",YES,@"dailyNotification", nil]; [userDefaults registerDefaults:defaultValues];
实际就是:
NSDictionary *defaultValues = [NSDictionary dictionaryWithObjectsAndKeys:0]; [userDefaults registerDefaults:defaultValues];
NSDictionary dictionaryWithObjectsAndKeys需要的参数是对象,这个时候,0与nil是等价的。