NSUserDefaults是一个轻量级本地数据存储,如果只是保存少量的数据,像用户名、密码这些建议用NSUserDefaults。
NSUserDefault支持的数据格式:NSNumber(NSInteger、Float、Double)、NSString、NSDate、NSArray、NSDictionary,BOOL类型。不能加入一个自定义类对象。NSUserDefault相当于一个迷你的数据库,执行后.plist文件会保存到/Users/mac-mini7/Library/Preferences/test_NSUserDefaults.plist
#import <Foundation/Foundation.h> #import "ObjectBase.h" int main(int argc, const char * argv[]) { @autoreleasepool { // insert code here... //初始化 NSUserDefaults *userDefaults11 = [NSUserDefaults standardUserDefaults]; //初始化 NSDate *date = [NSDate date]; NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; NSArray *array = [NSArray arrayWithObjects:@"hello",@"world",nil]; NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys: @"abc",@"111", @"efg",@"222", nil ]; //添加数据 [userDefaults setInteger:1 forKey:@"integer"]; [userDefaults setFloat:2.0 forKey:@"float"]; [userDefaults setDouble:3.0 forKey:@"double"]; [userDefaults setBool:YES forKey:@"bool"]; [userDefaults setObject:@"string" forKey:@"string"]; [userDefaults setObject:date forKey:@"date"]; [userDefaults setObject:array forKey:@"array"]; [userDefaults setObject:dictionary forKey:@"dictionary"]; [userDefaults removeObjectForKey:@"aaaa"]; [userDefaults removeObjectForKey:@"111"]; //存储到本地磁盘 [userDefaults synchronize]; //读数据 NSInteger i = [userDefaults11 integerForKey:@"integer"]; float f = [userDefaults11 floatForKey:@"float"]; double d = [userDefaults11 doubleForKey:@"double"]; BOOL b = [userDefaults11 boolForKey:@"bool"]; NSString *s = [userDefaults11 objectForKey:@"string"]; NSArray *array2 = [userDefaults11 objectForKey:@"array"]; NSDictionary *dictionary2 = [userDefaults11 objectForKey:@"dictionary"]; NSDate *date2 = [userDefaults11 objectForKey:@"date"]; NSLog(@"%@ %ld %f %f %d %@",date2,i,f,d,b,s); for (NSString *s in array2) { NSLog(@"array:%@",s); } NSString *s1 = [dictionary2 objectForKey:@"111"]; NSString *s2 = [dictionary2 objectForKey:@"222"]; NSLog(@"s1:%@ s2:%@",s1,s2); } return 0; }
输出结果:
2015-10-10 15:22:33.496 test_NSUserDefaults[1387:303] 2015-10-10 07:22:30 +0000 1 2.000000 3.000000 1 string
2015-10-10 15:22:33.496 test_NSUserDefaults[1387:303] array:hello
2015-10-10 15:22:33.497 test_NSUserDefaults[1387:303] array:world
2015-10-10 15:22:33.497 test_NSUserDefaults[1387:303] s1:abc s2:efg
总结:相对于配置xml文件来保存少了解析xml的过程,相对简便,若是要保存较少数据可以用NSUserDeauft,缺点是不能保存自定义类对象,只能保存有限的数据类型。