OC歸檔的對象裏面包括其餘類的屬性!

main.m

#import <Foundation/Foundation.h>atom

#import "FJPerson.h"spa

#import "FJCar.h".net

#define PATH @"/Users/IOS1601/Desktop/plist文件/personCar"3d


//若是須要歸檔的對象的屬性中又另一個類的對象,讓兩個類code

//都遵照NSCoding協議而且實現協議的方法,去歸檔和解歸檔相應的屬性;orm




int main(int argc, const char * argv[]) {對象

    @autoreleasepool {get

        FJPerson *person = [[FJPerson alloc]init];it

        person.name = @"fanjuan";io

    

        FJCar *car = [[FJCar alloc]init];

        car.color = @"yellow";

        car.price = 77777777;

        person.car = car;

        

        //歸檔

        

     //   [NSKeyedArchiver archiveRootObject:person

       //toFile:PATH];

        

    FJPerson *p = [NSKeyedUnarchiver unarchiveObjectWithFile:PATH];

        

        NSLog(@"車主%@  車顏色%@  車價格%.2lf",p.name,p.car.color,p.car.price);

    }

    return 0;

}

#pragma mark 歸檔



FJCar.h

#import <Foundation/Foundation.h>


@interface FJCar : NSObject <NSCoding>


//顏色

@property (nonatomic,copy) NSString *color;

//價格

@property (nonatomic,assign) double price;


@end


FJCar.m


#import "FJCar.h"


@implementation FJCar


- (void)encodeWithCoder:(NSCoder *)aCoder{

    

    [aCoder encodeObject:_color forKey:@"color"];

    

    [aCoder encodeDouble:_price forKey:@"price"];

    

}


- (instancetype) initWithCoder:(NSCoder *)aDecoder{

    if(self = [super init]){

    _color = [aDecoder decodeObjectForKey:@"color"];

    

    _price = [aDecoder decodeDoubleForKey:@"price"];

    }

    return self;

}



@end


FJPerson.h

#import <Foundation/Foundation.h>

@class FJCar;

@interface FJPerson : NSObject <NSCoding>


//姓名

@property (nonatomic,copy) NSString *name;

//

@property (nonatomic,strong) FJCar *car;

@end


FJCar.m


#import "FJCar.h"


@implementation FJCar


- (void)encodeWithCoder:(NSCoder *)aCoder{

    

    [aCoder encodeObject:_color forKey:@"color"];

    

    [aCoder encodeDouble:_price forKey:@"price"];

    

}


- (instancetype) initWithCoder:(NSCoder *)aDecoder{

    if(self = [super init]){

    _color = [aDecoder decodeObjectForKey:@"color"];

    

    _price = [aDecoder decodeDoubleForKey:@"price"];

    }

    return self;

}



@end

相關文章
相關標籤/搜索