遵循NSCoding協(xié)議
NSCoding協(xié)議聲明了兩個方法挽懦,這兩個方法是一定要實現(xiàn)的翰意。其中一個方法用來說明如何將對象編碼到歸檔中,另一個方法用來說明如何進(jìn)行解檔獲取新對象。
1. 遵循協(xié)議和設(shè)置屬性
@interface Student : NSObject<NSCoding>
/* 姓名 */
@property(nonatomic,copy)NSString *name;
/* 年齡 */
@property(nonatomic,assign)NSInteger age;
/* 身高 */
@property(nonatomic,assign)double height;
2. 實現(xiàn)協(xié)議方法一(歸檔冀偶,保存數(shù)據(jù))
- (void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:self.name forKey:@"name"];
[aCoder encodeInteger:self.age forKey:@"age"];
[aCoder encodeDouble:self.height forKey:@"height"];
}
3. 實現(xiàn)協(xié)議方法二(解檔醒第,讀取數(shù)據(jù))
- (id)initWithCoder:(NSCoder *)aDecoder
{
if (self = [super init]) {
self.name = [aDecoder decodeObjectForKey:@"name"];
self.age = [aDecoder decodeIntegerForKey:@"age"];
self.height = [aDecoder decodeDoubleForKey:@"height"];
}
return self;
}
- 特別注意
如果需要?dú)w檔的類是某個自定義類的子類時,就需要在歸檔和解檔之前先實現(xiàn)父類的歸檔和解檔方法进鸠。即 [super encodeWithCoder:aCoder] 和 [super initWithCoder:aDecoder] 方法;
使用
把對象歸檔是調(diào)用NSKeyedArchiver的工廠方法 archiveRootObject: toFile:
NSString *savePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"student.data"];
Student *student = [[Student alloc] init];
student.name = @"lily";
student.age = 25;
student.height = 166;
[NSKeyedArchiver archiveRootObject:student toFile:savePath];
從文件中解檔對象就調(diào)用NSKeyedUnarchiver的一個工廠方法 unarchiveObjectWithFile:
NSString *readerPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"student.data"];
Student *student = [NSKeyedUnarchiver unarchiveObjectWithFile:readerPath];
if (student) {
self.informationLable.text = [NSString stringWithFormat:@"該學(xué)生的姓名:%@,年齡:%ld,身高:%.2f",student.name,student.age,student.height];
}
注意
必須遵循并實現(xiàn)NSCoding協(xié)議
保存文件的擴(kuò)展名可以任意指定
繼承時必須先調(diào)用父類的歸檔解檔方法