自定義對象
- 首先創(chuàng)建一個
Person
類谱邪,繼承自NSObject
,需要遵守<NSCoding>
協(xié)議@interface Person : NSObject<NSCoding>
聲明一個name屬性@property(nonatomic,strong)NSString *name;
- 實現(xiàn)兩個代理方法
//當對象進行歸檔操作的時候,會自動調(diào)用該方法
-(void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:self.name forKey:@"name"];
}```
//當對象進行反歸檔的時候調(diào)用
-(instancetype)initWithCoder:(NSCoder *)aDecoder{`
if (self = [super init]) {
self.name = [aDecoder decodeObjectForKey:@"name"];
}return self;
}```
- 在視圖控制器里進行歸檔和反歸檔(即存入和取出數(shù)據(jù))
- 歸檔
//創(chuàng)建一個Person對象
Person *person = [[Person alloc] init];
person.name = @"小花";
//路徑
NSString *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *path = [documentPath stringByAppendingPathComponent:@"person.plist"];
//進行歸檔并存入
[NSKeyedArchiver archiveRootObject:person toFile:path];
- 反歸檔
//用一個Person對象接受反歸檔返回的對象
Person *per = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
存儲自定義對象的數(shù)組
數(shù)組內(nèi)存儲的對象也需要遵守
<NSCoding>
協(xié)議實現(xiàn)兩個代理方法贫奠,具體如上
- 視圖控制器內(nèi)
//創(chuàng)建兩個person對象
Person *person1 = [[Person alloc] init];
person1.name = @"huahua";
Person *person2 = [[Person alloc] init];
person2.name = @"peipei";
//將兩個person對象存入數(shù)組
NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:person1,person2, nil];
//獲取路徑
NSString *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *path = [documentPath stringByAppendingPathComponent:@"array.plist"];
//將數(shù)組進行歸檔并存入指定路徑
[NSKeyedArchiver archiveRootObject:array toFile:path];
//用一個數(shù)組接收反歸檔的數(shù)據(jù)
NSArray *arr = [NSKeyedUnarchiver unarchiveObjectWithFile:path];