归档

1.流程:

中介:NSMutableData(必须是新对象,里面不能有数据)

  • 存档-》编码-》写入路径。
  • 读取路径-》解档-》解码。

2. 可以 对集合、NSData、对象属性归档(写到**.xml本地文件)。

3.对象属性的"编码解码(类似kvc)":实现NSCoding协议的2个方法,存档、读取路径时自动调用。

-(void)encodeWithCoder:(NSCoder *)aCoder
-(id)initWithCoder:(NSCoder *)aDecoder

 Student.h

#import <Foundation/Foundation.h>

@interface Student : NSObject <NSCoding>
{
    NSString *_name;
    int _age;
}
@property(nonatomic,retain)NSString *name;
@property(nonatomic,assign)int age;
@end

Student.m

#import "Student.h"

@implementation Student
@synthesize name = _name,age = _age;

-(void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:_name  forKey:@"name"];
    [aCoder encodeInteger:_age forKey:@"age"];
}

-(id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super init];
    if (self)
    {
        self.name = [aDecoder decodeObjectForKey:@"name"];
        self.age = [aDecoder decodeIntegerForKey:@"age"];
    }
    return self;
}

@end

AppDelegate.m

    NSArray *arr = [NSArray arrayWithObjects:@"one",@"two",@"three", nil];
    //[arr writeToFile:PATH atomically:YES];
   //NSArray *arra = [NSArray arrayWithContentsOfFile:PATH]; NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"one",@"1",@"two",@"2",@"three",@"3", nil]; NSMutableData *mData = [[NSMutableData alloc]init]; //归档 NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:mData];//存档 [archiver encodeObject:arr forKey:@"arr"]; [archiver encodeObject:dic forKey:@"dic"]; [archiver finishEncoding]; [mData writeToFile:PATH atomically:YES];//写入路径 //解档 NSData *data = [NSData dataWithContentsOfFile:PATH];//读取路径 NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:data];//解档 NSDictionary *dictionary = [unarchiver decodeObjectForKey:@"dic"]; NSLog(@"%@",dictionary); //2.存对象属性 Student *s = [[Student alloc]init]; s.name = @"jobs"; s.age = 25; NSData * data1 = [NSKeyedArchiver archivedDataWithRootObject:s]; [data1 writeToFile:@"/Users/huen/Desktop/归档解档/p.rtf" atomically:YES]; NSData *data2 = [NSData dataWithContentsOfFile:@"/Users/huen/Desktop/归档解档/p.rtf"]; Student *stu = [NSKeyedUnarchiver unarchiveObjectWithData:data2]; NSLog(@"%@,%d",stu.name,stu.age);

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值