iOS数据持久化(二)-NSUserDefault

NSUserDefaults适合存储轻量级的本地数据,主要用于保存用户名、密码等常用资料。

主要保存数据类型:NSString、BOOL、NSInteger、Float、Double、NSArray、NSDictionary

保存数据

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

//保存字符串

[userDefaults setObject:@"张三" forKey:@"name"];

//保存整型

[userDefaults setInteger:26 forKey:@"age"];

//保存BOOL类型

BOOL result = YES;

[userDefaults setBool:result forKey:@"true"];

//保存数组

NSArray *array1 = @[@"张三",@"李四",@"王五"];

[userDefaults setObject:array1 forKey:@"array1"];

//保存字典

NSDictionary *dict1 = @{@"name":@"张三",@"age":@"26",@"job":@"工程师"};

[userDefaults setObject:dict1 forKey:@"dict1"];

//强制储存

[userDefaults synchronize];


读取数据

NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];

读取字符串

NSString *name = [userDefault objectForKey:@"name"];

读取整型

NSInteger age = [userDefault integerForKey:@"age"];

读取BOOL

BOOL result = [userDefault boolForKey:@"true"];

读取数组

NSArray *array1 = [userDefault objectForKey:@"array1"];

读取字典

NSDictionary *dict = [userDefault objectForKey:@"dict1"];

你可能感兴趣的:(iOS数据持久化(二)-NSUserDefault)