一、在我們自定義的物件的.h中宣告<NSCoding>這個Protocol。
二、在我們的物件的.m檔中,實作<NSCoding>中的這二個方法(required),程式碼中的_userName和_phone是這個自定義物件(member)的property
//將property編碼為binary code file
- (void)encodeWithCoder:(NSCoder *)coder {
[super encodeWithCoder:coder];
[coder encodeObject:_userName forKey:@"user_name"];
[coder encodeInteger:_phone forKey:@"phone"];
}
//將property從binary code file中解碼
- (id)initWithCoder:(NSCoder *)coder {
self = [super initWithCoder:coder];
_userName = [coder decodeObjectForKey:@"user_name"];
_phone = [coder decodeIntegerForKey:@"phone"];
}
三,使用下列的方式來操作這個自定義物件:
//儲存
BOOL result = [NSKeyedArchiver archiveRootObject:member toFile:path];
//讀取
Member *member = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
沒有留言:
張貼留言