iOS 自定义的对象类型的解档和归档

自定义的对象的解档和归档

 


如果想对自己自定义的类进行解档和归档的话 必须遵循一个协议:NSCoding

Student.h 文件

#import <Foundation/Foundation.h>

@interface Student : NSObject<NSCoding>
@property(nonatomic,strong)NSString *name;
@property(nonatomic,assign)int age;

-(instancetype)initWithName:(NSString *)name AndAge:(int)age;

@end

Student.m 文件

#import "Student.h"

@implementation Student


- (instancetype)initWithName:(NSString *)name AndAge:(int)age
{
    self = [super init];
    if (self) {
        _age=age;
        _name=name;
    }
    return self;
}
//解答时候调用 是一个初始化的方法
-(instancetype)initWithCoder:(NSCoder *)aDecoder{

    self=[super init];
    if (self) {
        _name=[aDecoder decodeObjectForKey:@"name"];
        _age=(int)[aDecoder decodeIntegerForKey:@"age"];
    }
    return self;
}

//归档调用该方法
-(void)encodeWithCoder:(NSCoder *)aCoder{

    NSLog(@"encodeWithCoder");
    [aCoder encodeObject:_name forKey:@"name"];
    [aCoder encodeInteger:_age forKey:@"age"];
    
}

-(NSString *)description{
    return [NSString stringWithFormat:@"name=%@,age=%d",_name,_age];
}


@end

客户端代码

#import "ViewController.h"
#import "Student.h"
#define PATH [NSHomeDirectory() stringByAppendingPathComponent:@"Student.qll"]
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    NSLog(@"%@",PATH);
    
    Student *stu=[[Student alloc]init];
    stu.name=@"张F";
    stu.age=13;

    NSLog(@"%@",stu);
    //归档
  BOOL bol=[NSKeyedArchiver archiveRootObject:stu toFile:PATH];
    
    if (bol==1) {
        NSLog(@"归档成功");
    }

    //解档
    
    Student *stu1=[NSKeyedUnarchiver unarchiveObjectWithFile:PATH];
    NSLog(@"%@",stu1);

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

运行结果:

 

posted @ 2016-03-21 17:47  徒步天涯  阅读(837)  评论(0编辑  收藏  举报