1.將某個對象寫入文件時會調(diào)用*在這個方法中說清楚哪些屬性需要存儲
- (void)encodeWithCoder:(NSCoder*)encoder
{
[encoderencodeObject:self.noforKey:@"no"];
[encoderencodeInt:self.ageforKey:@"age"];
[encoderencodeDouble:self.heightforKey:@"height"];
}
2.*從文件中解析對象時會調(diào)用在這個方法中說清楚哪些屬性需要存儲
- (id)initWithCoder:(NSCoder*)decoder
{
if(self= [superinit]) {
//讀取文件的內(nèi)容
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];