- (void)viewDidLoad {
[super viewDidLoad];
//需求一:不同的类型数据存入文件
//1.准备数据
NSArray *array = @[@"Bob", @20, @[@"Shell", @"Python", @"Objective-C"]];
BOOL isLogIn = YES;
NSInteger gradeValue = 4;
//2.获取单例对象,选择方法,指定不同的key
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:array forKey:@"arrayKey"];
[defaults setBool:isLogIn forKey:@"isLogInKey"];
[defaults setInteger:gradeValue forKey:@"gradeValueKey"];
//3.调用同步方法(强制写入文件)
[defaults synchronize];
//需求二:将存入的数据读取出来
//1.获取单例对象,给定key(取决于存入指定key), 选择方法
NSArray *readArray = [defaults objectForKey:@"arrayKey"];
BOOL readLogIn = [defaults boolForKey:@"isLogInKey"];
NSInteger readInteger = [defaults integerForKey:@"gradeValueKey"];
//验证
NSLog(@"array:%@; bool:%d; integer:%ld", readArray, readLogIn, (long)readInteger);
//了解:可以删除指定key的value值
[defaults removeObjectForKey:@"gradeValueKey"];
}
网友评论