1.将某个对象写入文件时会调用*在这个方法中说清楚哪些属性需要存储
- (void)encodeWithCoder:(NSCoder*)encoder
{
[encoderencodeObject:self.noforKey:@"no"];
[encoderencodeInt:self.ageforKey:@"age"];
[encoderencodeDouble:self.heightforKey:@"height"];
}
2.*从文件中解析对象时会调用在这个方法中说清楚哪些属性需要存储
- (id)initWithCoder:(NSCoder*)decoder
{
if(self= [superinit]) {
//读取文件的内容
self.no= [decoderdecodeObjectForKey:@"no"];
self.age= [decoderdecodeIntForKey:@"age"];
self.height= [decoderdecodeDoubleForKey:@"height"];
}
returnself;
}
// 2.归档模型对象
// 2.1.获得Documents的全路径
NSString*doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)lastObject];
// 2.2.获得文件的全路径
NSString*path = [docstringByAppendingPathComponent:@"stu.data"];
// 2.3.将对象归档
[NSKeyedArchiverarchiveRootObject:stutoFile:path];
NSString*doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)lastObject];
// 2.获得文件的全路径
NSString*path = [docstringByAppendingPathComponent:@"stu.data"];
// 3.从文件中读取MJStudent对象
MJStudent*stu = [NSKeyedUnarchiverunarchiveObjectWithFile:path];
网友评论