iPhone存储数据一般有三种方式:数据库,NSUserDefaults和文件。
其中NSUserDefaults适合存储数据量小的数据,例如用户配置。并不是所有的东西都能往里面放,只支持:NSString, NSNumber, NSData, NSArray, NSDictionary。
//creat NSUserDefaults
NSUserDefaults *userdefaults = [NSUserDefaults standardUserDefaults];
//add objects
[userdefaults setBool:NO forKey:@"boolKey"];
[userdefaults setValue:@"hello" forKey:@"stringKey"];
NSArray *arr = [NSArray arrayWithObjects:@"one",@"three",@"two", nil];
[userdefaults setValue:arr forKey:@"arrayKey"];
//remove objects
[userdefaults removeObjectForKey:@"stringKey"];
//为了确保数据被保存到disk(不写的话也会保存)
[userdefaults synchronize];
//get objects
BOOL ok = [userdefaults boolForKey:@"boolKey"];
NSArray *array = [userdefaults objectForKey:@"arrayKey"];
如果存储自定义对象,需要将对象转换成NSData,然后存入userdefaults。
@interface People : NSObject <NSCoding>
{
NSString *_name;
NSString *_age;
}
@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSString *age;
@end;
@implementation People
@synthesize name = _name, age = _age;
- (id) initWithCoder: (NSCoder *)coder
{
if (self = [super init])
{
self.name = [coder decodeObjectForKey:@"name"];
self.age = [coder decodeObjectForKey:@"age"];
}
return self;
}
- (void) encodeWithCoder: (NSCoder *)coder
{
[coder encodeObject:self.name forKey:@"name"];
[coder encodeObject:self.age forKey:@"age"];
}
@end
//将对象转换成NSData,然后存入NSUserDefaults
People *people = [[People alloc] init];
people.name = @"lilei";
people.age = @"18";
NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
NSData *peopleData = [NSKeyedArchiver archivedDataWithRootObject:people];
//save peopleData
[userDefault setObject:peopleData forKey:@"peopleKey"];
//get Data
peopleData = [userDefault objectForKey:@"peopleKey"];
people = [NSKeyedUnarchiver unarchiveObjectWithData:peopleData];
在模拟器下你可以在下面地址看到你所存储的内容:
Library/Application Support/iPhone Simulator/6.1/Application/[your project]/Library/Preferences/[XXXX.plist]