归档

1.流程:

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

2.对象属性的"编码解码(类似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];
    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);
归档

归档

上一篇:serenity 开发框架(Net Core 2.2 C#)


下一篇:windows子系统(WSL)root或者普通用户密码忘记,如何修改?