归档和解归档

基本数据持久化:把OC中的基本数据存储到沙盒中。
归档:把复杂类型转为data类型的过程。
解归档:把data类型转为复杂类型的过程。
NSCoding



//======car.h========
#import 

@interface YTCar : NSObject 
//颜色
@property(nonatomic, copy) NSString * color;
//价格
@property(nonatomic, assign) double price;

@end


//========car.m==========
#import "YTCar.h"

@implementation YTCar

//将所有属性归档
- (void)encodeWithCoder:(NSCoder *)aCoder{

    [aCoder encodeObject:_color forKey:@"color"];
    
    [aCoder encodeDouble:_price forKey:@"price"];
}

//将所有属性解归档
- (id)initWithCoder:(NSCoder *)aDecoder{

    if (self = [super init]) {
        
        _color = [aDecoder decodeObjectForKey:@"color"];
        _price = [aDecoder decodeDoubleForKey:@"price"];
    }
    
    return self;
}

@end


#import 
@class YTCar;

@interface YTPerson : NSObject 
//姓名
@property(nonatomic, copy) NSString * name;

//车
@property(nonatomic, strong) YTCar * car;


@end


//=======preson.m========

#import "YTPerson.h"
#import "YTCar.h"

@implementation YTPerson

//将所有希望归档的属性都归档
- (void)encodeWithCoder:(NSCoder *)aCoder{

    [aCoder encodeObject:_name forKey:@"name"];
    [aCoder encodeObject:_car forKey:@"car"];
}

//解归档
- (id)initWithCoder:(NSCoder *)aDecoder{

    if (self = [super init]) {
        
        _name = [aDecoder decodeObjectForKey:@"name"];
        _car = [aDecoder decodeObjectForKey:@"car"];
        
    }
    
    return self;
}

@end


//=====main========

#import 
#import "YTPerson.h"
#import "YTCar.h"

#define PATH @"/Users/yuting/Desktop/授课/CD1601/OC阶段/day5-归档和解归档/Person"

//如果需要归档的对象的属性中有另外一个类的对象,让两个类都遵守NSCoding协议并且实现协议方法,去归档和解归档相应的属性。
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        
        YTPerson * person = [[YTPerson alloc] init];
        person.name = @"小明";
        
        YTCar * bee = [[YTCar alloc] init];
        bee.color = @"yellow";
        bee.price = 50;
        
        person.car = bee;
        
        //归档
//        [NSKeyedArchiver archiveRootObject:person toFile:PATH];
        
        //解归档
        YTPerson * p = [NSKeyedUnarchiver unarchiveObjectWithFile:PATH];
        
        NSLog(@"%@ %@ %lf", p.name, p.car.color,p.car.price);
        
        
    }
    return 0;
}

你可能感兴趣的:(归档和解归档)