每次歸檔對象時,都會調用這個方法。一般在這個方法裏面指定如何歸檔對象中的每個實例變量,可以使用encodeObject:forKey:方法歸檔實例變量。
每次從文件中恢復(解碼)對象時,都會調用這個方法。一般在這個方法裏面指定如何解碼文件中的數據爲對象的實例變量,可以使用decodeObject:forKey方法解碼實例變量。
NSArray*array = [NSArray arrayWithObjects:@”a”,@”b”,nil];
[NSKeyedArchiver archiveRootObject:array toFile:path];
NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
4. 自定義對象歸檔/解檔總結:
1.如果要存儲自定義對象一定要用“歸檔/解檔”的操作;
2.plist.偏好設置都不能用來存儲自定義的對象;
3.自定義對象歸檔/解檔的時候一定要遵守<NSCoding>的協議;
4.只要解析文件都會調用initWithCoder:的方法;
5.在解檔屬性的時候,記得給屬性賦值!!!!
6.爲什麼要遵守<NSCoding>協議? 爲了告訴系統歸檔/解檔哪些屬性,告訴系統如何進行歸檔解檔。
6. 一個自定義對象的歸檔解檔Demo:
==================創建一個遵守 NSCoding 協議的類=========================
@interface Teacher : NSObject <NSCoding>
@property (nonatomic, assign) int age;
@property (nonatomic, copy) NSString* name;
@end
#import "Teacher.h"
@implementation Teacher
// 告訴系統需要歸檔哪些屬性
- (void)encodeWithCoder:(NSCoder*)aCoder
{
[aCoder encodeInt:_age forKey:@"age111111"];
[aCoder encodeObject:_name forKey:@"name"];
}
// 告訴系統解檔哪些屬性
- (id)initWithCoder:(NSCoder*)aDecoder
{
if (self = [super init]) {
_age = [aDecoder decodeIntForKey:@"age111111"];
_name = [aDecoder decodeObjectForKey:@"name"];
}
return self;
}
@end
==================創建一個導入了 自定義Teacher類的控制器 ViewController =========================
#import "ViewController.h"
#import "Teacher.h"
@interface ViewController ()
@end
@implementation ViewController
// 存數據
- (IBAction)save:(id)sender
{
// tmp
NSString* tmpPath = NSTemporaryDirectory();
NSString* filePath = [tmpPath stringByAppendingPathComponent:@"teacher.data"];
Teacher* t = [[Teacher alloc] init];
t.name = @"傳智播客";
t.age = 18;
[NSKeyedArchiver archiveRootObject:t toFile:filePath];
}
// 取數據
- (IBAction)read:(id)sender
{
NSString* tmpPath = NSTemporaryDirectory();
NSString* filePath = [tmpPath stringByAppendingPathComponent:@"teacher.data"];
Teacher* t = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
NSLog(@"%d", t.age);
}