main.m
#import <Foundation/Foundation.h>
#import "FJPerson.h"
#import "FJCar.h"
#define PATH @"/Users/IOS1601/Desktop/plist文件/personCar"
//如果需要归档的对象的属性中又另外一个类的对象,让两个类
//都遵守NSCoding协议并且实现协议的方法,去归档和解归档相应的属性;
int main(int argc, const char * argv[]) {
@autoreleasepool {
FJPerson *person = [[FJPerson alloc]init];
person.name = @"fanjuan";
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