1,在使用plist进行数据存储和读取,只适用于系统自带的一些常用类型才能用,且必须先获取路径相对麻烦;
2,偏好设置(将所有的东西都保存在同一个文件夹下面,且主要用于存储应用的设置信息)
3,归档:因为前两者都有一个致命的缺陷,只能存储常用的类型(不过😄)。归档可以实现把自定义的对象存放在文件中。
http://www.jianshu.com/p/fef61b1ab7a1
Model
#import <Foundation/Foundation.h>
// 如果想将一个自定义对象保存到文件中必须实现NSCoding协议
@interface UserModel : NSObject<NSCoding>
///用户ID
@property (nonatomic , assign) NSInteger identifie;
///姓名
@property (nonatomic , copy) NSString * name;
///性别
@property (nonatomic , copy) NSString * sex;
///年龄
@property (nonatomic , assign) NSInteger age;
///手机
@property (nonatomic , copy) NSString * mobile;
///头像ID
@property (nonatomic , assign) NSInteger image_id;
///头像路径
@property (nonatomic , copy) NSString * image_path;
@end
#import "UserModel.h"
@implementation UserModel
// 当将一个自定义对象保存到文件的时候就会调用该方法
// 在该方法中说明如何存储自定义对象的属性
// 也就说在该方法中说清楚存储自定义对象的哪些属性
-(void)encodeWithCoder:(NSCoder *)aCoder
{
NSLog(@"调用了encodeWithCoder:方法");
[aCoder encodeInteger:self.identifie forKey:@"identifie"];
[aCoder encodeObject:self.name forKey:@"name"];
[aCoder encodeInteger:self.age forKey:@"age"];
[aCoder encodeObject:self.sex forKey:@"sex"];
[aCoder encodeObject:self.mobile forKey:@"mobile"];
[aCoder encodeInteger:self.image_id forKey:@"image_id"];
[aCoder encodeObject:self.image_path forKey:@"image_path"];
}
// 当从文件中读取一个对象的时候就会调用该方法
// 在该方法中说明如何读取保存在文件中的对象
// 也就是说在该方法中说清楚怎么读取文件中的对象
-(id)initWithCoder:(NSCoder *)aDecoder
{
NSLog(@"调用了initWithCoder:方法");
//注意:在构造方法中需要先初始化父类的方法
if (self=[super init]) {
self.identifie=[aDecoder decodeIntegerForKey:@"identifie"];
self.name=[aDecoder decodeObjectForKey:@"name"];
self.age=[aDecoder decodeIntegerForKey:@"age"];
self.sex=[aDecoder decodeObjectForKey:@"sex"];
self.mobile=[aDecoder decodeObjectForKey:@"mobile"];
self.image_id=[aDecoder decodeIntegerForKey:@"image_id"];
self.image_path=[aDecoder decodeObjectForKey:@"image_path"];
}
return self;
}
@end
VC
- (IBAction)add:(UIButton *)sender {
UserModel * model = [[UserModel alloc]init];
model.identifie = 1111;
model.name = @"刘哥哥";
model.sex = @"男";
model.age = 23;
model.mobile = @"13612345678";
model.image_id = 123;
model.image_path = @"http://ww2.sinaimg.cn/mw690/95a6ddc2gw1f9pl2eeycpj20j60l7mz7.jpg";
NSString * path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject]stringByAppendingPathComponent:@"user.text"];
NSLog(@"%@",path);
//将自定义的对象保存到文件中
[NSKeyedArchiver archiveRootObject:model toFile:path];
}
- (IBAction)search:(UIButton *)sender {
NSString * path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject]stringByAppendingPathComponent:@"user.text"];
NSLog(@"path=%@",path);
//2.从文件中读取对象
UserModel * model =[NSKeyedUnarchiver unarchiveObjectWithFile:path];
NSLog(@"%@",model.name);
}