自定义类型的归档解档

首先创建一个自定义的类

#import <Foundation/Foundation.h>

 

@interface Student : NSObject

//定义学生类型的几个属性

@property(strong,nonatomic)NSString *name;

@property(assign,nonatomic)int age;

@property(strong,nonatomic)NSString *addr;

@end

 

#import <UIKit/UIKit.h>

#import "Student.h"

//用宏定义定义一个文件名

#define  PATH [ NSHomeDirectory() stringByAppendingPathComponent:@"student.ajb"]

@interface ViewController : UIViewController

//定义一个归档按钮

@property(strong,nonatomic)UIButton *btn;

//定义一个解档按钮

@property(strong,nonatomic)UIButton *btn1;

@end

 

#import "ViewController.h"

 

@interface ViewController ()

 

@end

 

@implementation ViewController

 

- (void)viewDidLoad {

    [super viewDidLoad];

    //输出文件地址

    NSLog(@"%@",PATH);

   //对按钮初始化

    self.btn=[UIButton buttonWithType:UIButtonTypeRoundedRect];

    //指定按钮在视图上的位置及大小

    self.btn.frame=CGRectMake(100, 100, 100, 50);

    //为按钮添加颜色

    self.btn.backgroundColor=[UIColor greenColor];

    //给按钮定义一个名称

    [self.btn setTitle:@"归档" forState:UIControlStateNormal];

    [self.view addSubview:self.btn];

    //按钮监听方法

    [self.btn addTarget:self action:@selector(test) forControlEvents:UIControlEventTouchUpInside];

    

    self.btn1=[UIButton buttonWithType:UIButtonTypeRoundedRect];

    self.btn1.frame=CGRectMake(100, 200, 100, 50);

    self.btn1.backgroundColor=[UIColor greenColor];

    [self.btn1 setTitle:@"解档" forState:UIControlStateNormal];

    [self.view addSubview:self.btn1];

    [self.btn1 addTarget:self action:@selector(texta) forControlEvents: UIControlEventTouchUpInside];

    

}

//归档方法

-(void)test

{//初始化一个学生类型的对象 并给学生的属性赋值

    Student *stu=[[Student alloc]init];

    stu.name=@"zhangsan";

    stu.age=32;

    stu.addr=@"guiyang";

    NSMutableData *data=[NSMutableData data];

    NSKeyedArchiver *archiver=[[NSKeyedArchiver alloc] initForWritingWithMutableData:data];

    [archiver encodeObject:stu.name forKey:@"stu.name"];

    [archiver encodeInt:stu.age forKey:@"stu.age"];

    [archiver encodeObject:stu.addr forKey:@"stu.addr"];

    [archiver finishEncoding];

    BOOL bol=[data writeToFile:PATH atomically:YES];

    NSLog(@"%d",bol);

}

//解档

-(void)texta

{

    NSData *data=[NSData dataWithContentsOfFile:PATH];

    NSKeyedUnarchiver *unarchiver=[[NSKeyedUnarchiver alloc] initForReadingWithData:data];

    NSString *str=[unarchiver decodeObjectForKey:@"stu.name"];

     NSString *str1=[unarchiver decodeObjectForKey:@"stu.addr"];

    int age=(int)[unarchiver decodeIntForKey:@"stu.age"];

    NSLog(@"stu.name=%@\nstu.addr=%@\nage=%d",str,str1,age);

}

- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

 

@end

 

posted @ 2016-03-21 21:35  清浅晨曦  阅读(138)  评论(0编辑  收藏  举报