数据持久化存储--序列化&反序列化

//存储没有实现NSCoding协议的数据/

//可以直接写入文件的:字符串,数组,字典,(基本数据类型转化为number对象)number二进制数据

//序列化(存储):需要存储没有实现NSCoding协议的对象类型,需要先把对象序列化为二进制数据然后再把二进制数据写入文件

//反序列化(读取) :先从文件中读取出二进制数据然后对二进制数据进行反序列为对应的类型

在模型的类中.m

在模型的类中导入NSCoding并声明属性.h并

@interface People :NSObject

@property (nonatomic,copy) NSString * name;

@property (nonatomic,assign) int age;

在模型的类中.m

//编码协议序列化

- (void)encodeWithCoder:(NSCoder*)aCoder {

//使用编码器aCoder对属性进行编码

[aCoder encodeInt:_age forKey:@"nine"];

//可以使用对应类型的编码方法

[aCoder encodeObject:_name forKey:@"mingzi"];

}

//解码协议反序列化

- (id)initWithCoder:(NSCoder *)aDecoder {

//判断父类是否调用了init方法

if(self= [super init]) {

//使用解码器aDecoder对属性进行解码

self.age=  [aDecoder decodeIntForKey:@"nine"];

self.name= [aDecoder decodeObjectForKey:@"mingzi"];

//        [aDecoder decodeIntForKey:@"nine"];

//        [aDecoder decodeObjectForKey:@"mingzi"];

}

return self;

}

//在viewDidLoad中

- (void)viewDidLoad {

[super viewDidLoad];

//初始化存放people对象的数组

NSMutableArray * array = [NSMutableArray array];

//找存储位置

NSString * FilePath = [self getFilePath];

for(int i = 0; i < 3; i ++) {

People * p = [[People alloc] init];

p.name= [NSString stringWithFormat:@"%d-name",i];

p.age= i + 20;

[array addObject:p];

NSLog(@"%@",p.name);

NSLog(@"%d",p.age);

}

//序列化为二进制数据

NSData * data = [NSKeyedArchiver archivedDataWithRootObject:array];

//写入文件

[data writeToFile:FilePath atomically:YES];

NSLog(@"%@",FilePath);

//传参读取数据

[self getDataWith:FilePath];

}

-(void)getDataWith:(NSString*)path {

//根据文件路径读取二进制数组

NSData *data = [NSData dataWithContentsOfFile:path];

NSMutableArray * array = [NSKeyedUnarchiver unarchiveObjectWithData:data];

NSLog(@"%@",array);

People *p = array[1];

NSLog(@"%@",p.name);

}

- (NSString *)getFilePath {

NSString *homeFilePath =NSHomeDirectory();

NSString *FilePath = [homeFilePath stringByAppendingString:@"/Documents/arrayFilePath.plist"];

return FilePath;

}

你可能感兴趣的:(数据持久化存储--序列化&反序列化)