自定義對象歸檔(解檔)

首先自定義一個Person對象
person.h裏的內容 (注意要遵守NSCoding協議)

@interface Person : NSObject <NSCoding>

@property (nonatomic,copy) NSString *name;
@property (nonatomic,assign) NSUInteger age;

@end

Person.m裏要實現歸檔、解檔的方法

@implementation Person

// 在對象歸檔的時候調用
// 那些屬性需要歸檔
// 這些屬性怎麼歸檔
- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:_name forKey:@"name"];
    [aCoder encodeInteger:_age forKey:@"age"];
}

// 在對象解檔的時候調用
// 哪些屬性需要解檔
// 這些屬性怎麼解檔
- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    if (self = [super init]) {

        _name = [aDecoder decodeObjectForKey:@"name"];
        _age = [aDecoder decodeIntegerForKey:@"age"];

    }
    return self;
}
@end

在SB中設置兩個Button,存儲和讀取。然後在ViewController.m中實現它們的點擊事件

- (IBAction)save:(UIButton *)sender
{
    // 定義一個Person對象
    Person *p1 = [[Person alloc] init];
    p1.name = @"zhansan";
    p1.age = 20;

    // 獲得Cache的路徑
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];

    // 拼接文件路徑
    NSString *filePath = [cachePath stringByAppendingPathComponent:@"person.data"];

    // 歸檔Person對象
    [NSKeyedArchiver archiveRootObject:p1 toFile:filePath];


}
- (IBAction)read:(UIButton *)sender
{
    // 獲得Cache的路徑
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];

    // 拼接文件路徑
    NSString *filePath = [cachePath stringByAppendingPathComponent:@"person.data"];

    // 解檔Person對象
    Person *p = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];

    NSLog(@"%@",p.name);
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章