iOS 归档、解档

.h文件

@interface Person : NSObject<NSCoding>

{

    NSString *name;

    int age;

    NSString *phone;

}

@property(nonatomic,retain)NSString *name, *phone;

@property(nonatomic,assign)int age;

// 初始化方法

-(id)initWithName:(NSString *)aName phone:(NSString *)aPhone age:(int)aAge;

@end


.m文件

#import "Person.h"

@implementation Person

@synthesize name,age,phone;

-(id)initWithName:(NSString *)aName phone:(NSString *)aPhone age:(int)aAge

{

    [super init];

    if (self) {

        self.name = aName;

        self.phone = aPhone;

        self.age = aAge;

    }

    return self;

    

}

- (void)encodeWithCoder:(NSCoder *)aCoder //将属性进行编码

{

    [aCoder encodeObject:self.name forKey:@"name"];

    [aCoder encodeObject:self.phone forKey:@"phone"];

    [aCoder encodeInteger:self.age forKey:@"age"];

    

}

- (id)initWithCoder:(NSCoder *)aDecoder //将属性进行解码

{

    NSString *name1 = [aDecoder decodeObjectForKey:@"name"];

    NSString *phone1 = [aDecoder decodeObjectForKey:@"phone"];

    int age1 = [aDecoder decodeIntegerForKey:@"age"];

    

    [self initWithName:name1 phone:phone1 age:age1];    

    

    return self;   

}

@end


主程序中进行归档与反归档


- (void)loadView

{

    self.view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 460)];

    self.view.backgroundColor = [UIColor whiteColor];

    

    Person *p1 = [[Person alloc]initWithName:@"jim" phone:@"654789" age:3];

    Person *p2 = [[Person alloc]initWithName:@"tom" phone:@"5464" age:4];

    //文件的归档

    NSMutableData *data = [NSMutableData data ];

    //创建一个归档类

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

    [archiver encodeObject:p1 forKey:@"Person1"];

    [archiver encodeObject:p2 forKey:@"Person2"];

    [archiver finishEncoding];

    [archiver release];

    //将数据写入文件里

    [data writeToFile:[self filePath] atomically:YES];

    //反归档,从文件中取出数据

    NSMutableData *data1 = [NSMutableData dataWithContentsOfFile:[self filePath]];

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

    Person *p3  = [unarchiver decodeObjectForKey:@"Person1"];

    Person *p4 =  [unarchiver decodeObjectForKey:@"Person2"];

    NSLog(@"%@ %@ %d",p3.name,p3.phone,p3.age);

    NSLog(@"%@ %@ %d",p4.name,p4.phone,p4.age);

}


-(NSString *)filePath

{

    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDirectory, YES)objectAtIndex:0];

    NSString *path = [docPath stringByAppendingPathComponent:@"texts"];


 //  NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches/texts"]; //两种方法都可以


    

    return path;

}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值