Plist文件
如果对象是NSString、NSDictionary、NSArray、NSData、NSNumber等类型,就可以使用writeToFile:atomically:方法直接将对象写到属性列表文件中
写入plist文件
// 将数据封装成字典
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:@"母鸡" forKey:@"name"];
[dict setObject:@"15013141314" forKey:@"phone"];
[dict setObject:@"27" forKey:@"age"];
// 将字典持久化到Documents/stu.plist文件中
[dict writeToFile:path atomically:YES];
plist文件读取
// 读取Documents/stu.plist的内容,实例化NSDictionary
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
NSLog(@"name:%@", [dict objectForKey:@"name"]);
NSLog(@"phone:%@", [dict objectForKey:@"phone"]);
NSLog(@"age:%@", [dict objectForKey:@"age"]);
.
.
NSUserDefaults
很多iOS应用都支持偏好设置,
比如保存用户名、密码、字体大小等设置
iOS提供了一套标准的解决方案来为应用加入偏好设置功能。
每个应用都有个NSUserDefaults实例,通过它来存取偏好设置。
比如,保存用户名、字体大小、是否自动登录
如果对象是NSString、NSDictionary、NSArray、NSData、NSNumber等类型,就可以使用writeToFile:atomically:方法直接将对象写到属性列表文件中
保存用户偏好设置
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
// 保存用户偏好设置
[defaults setBool:self.one.isOn forKey:@"one"];
[defaults setBool:self.two.isOn forKey:@"two"];
// 注意:UserDefaults设置数据时,不是立即写入,而是根据时间戳定时地把缓存中的数据写入本地磁盘。所以调用了set方法之后数据有可能还没有写入磁盘应用程序就终止了。
// 出现以上问题,可以通过调用synchornize方法强制写入
// 现在这个版本不用写也会马上写入 不过之前的版本不会
[defaults synchronize];
读取用户偏好设置
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
self.one.on = [defaults boolForKey:@"one"];
self.two.on = [defaults boolForKey:@"two"];
.
.
NSKeyedArchiver归档(NSCoding)
不是所有的对象都可以直接用这种方法进行归档,只有遵守了NSCoding协议的对象才可以。
如果父类也遵守了NSCoding协议,请注意:
- 应该在encodeWithCoder:方法中加上一句
[super encodeWithCode:encode];
确保继承的实例变量也能被编码,即也能被归档
- 应该在initWithCoder:方法中加上一句
self = [super initWithCoder:decoder];
确保继承的实例变量也能被解码,即也能被恢复
NSCoding协议有2个方法:
encodeWithCoder:
initWithCoder:
归档自定义Person类
//Person.h
@interface Person : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) int age;
@property (nonatomic, assign) float height;
@end
@implementation Person
- (void)encodeWithCoder:(NSCoder *)encoder {
[encoder encodeObject:self.name forKey:@"name"];
[encoder encodeInt:self.age forKey:@"age"];
[encoder encodeFloat:self.height forKey:@"height"];
}
- (id)initWithCoder:(NSCoder *)decoder {
self.name = [decoder decodeObjectForKey:@"name"];
self.age = [decoder decodeIntForKey:@"age"];
self.height = [decoder decodeFloatForKey:@"height"];
return self;
}
@end
归档(编码)
Person *person = [[Person alloc] init];
person.name = @"hosea";
person.age = 22;
person.height = 1.83f;
[NSKeyedArchiver archiveRootObject:person toFile:path];
恢复(解码)
Person *person = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
.
.
SQLite数据库
平时项目,我通常会选择这个进行本地缓存。
结合FMDB库来操作使用SQLite数据库。
网友评论