普通类型的归档方法

归档: 名副其实的就是把所有东西归纳在一个文档或者文件里面, 当我们需要的时候才拿到编译器使用, 这个就和我们从网上下载视频到硬盘, 需要的时候再用播放器打开一样.

PS: 归档之后的文件不能正常的打开, 只能用CMD或者是编译器的一些代码读取并且释放, 注意, 是先读取后释放, 不然释放在读取前面, 就会找不到文件或者文档所在的路径, 从而无法还原代码.

下面是简单的文件归档和读取释放的例子:

Human.h文件

#import <Foundation/Foundation.h>

@interface Human : NSObject <NSCoding>  //注意, 这里必须得声明一个归档的协议
//NSCoding协议要必须实现两个方法
//- (void)encodeWithCoder:(NSCoder *)aCoder;
//编码给定文档接收者使用。(必需)

//- (id)initWithCoder:(NSCoder *)aDecoder;
//返回一个对象的初始化数据在给定文档。(必需)
//你必须返回自我与编码器:init。如果你有一个先进的需要,需要替换一个解码后不同的
//对象,你可以在清醒后使用编码器:。
{
@private    //声明私有的实例变量
    int age;
    NSString *name;
    Human *child;
}

@property (nonatomic, assign)int age;   //定义int类型的age属性.
@property (nonatomic, copy)NSString *name;  //定义NSString类型的name属性.
@property (nonatomic, retain)Human *child;  //定义human指针类型child.

@end

Human.m文件

#import "Human.h"

@implementation Human

@synthesize age;
@synthesize name;
@synthesize child;

- (void) encodeWithCoder:(NSCoder *)aCoder  //为了归档而重写的方法.
{
    [aCoder encodeInt:age forKey:@"age"];
    [aCoder encodeObject:name forKey:@"name"];
    [aCoder encodeObject:child forKey:@"child"];
}

- (id)initWithCoder:(NSCoder *)aDecoder //为了解档而重写的方法.
{
    if(self = [super init]){
        self.age = [aDecoder decodeIntForKey:@"age"];
        //根据intforkey来解档age
        self.name = [aDecoder decodeObjectForKey:@"name"];
        //根据objectforkey来解档name
        self.child = [aDecoder decodeObjectForKey:@"child"];
        //根据objectforkey来解档child
    }
    return self;
}
@end

main.m文件

#import <Foundation/Foundation.h>
#import "Human.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
//        NSLog(@"Hello, World");
        
        Human *human1 = [Human new];
        Human *human2 = [Human new];
        
        human1.age = 20;
        human1.name = @"xiaoming";
        human1.child = human2;
        
        NSData *data1 = [NSKeyedArchiver archivedDataWithRootObject:human1];
        [data1 writeToFile:@"/Users/Cain/Desktop/Objective-C/实验代码/归档/Human/human.txt" atomically:YES];
        //writetofile表示的是用来存储文档路径的方法.
        
        NSData *data2 = [NSData dataWithContentsOfFile:@"/Users/Cain/Desktop/Objective-C/实验代码/归档/Human/human.txt"];
        //datawithcontentsoffile是用来读取文档路径的方法.
        
        Human *human3 = [NSKeyedUnarchiver unarchiveObjectWithData:data2];
        //unarchiveobjectwithdata是用来还原文档的方法.
        
        NSLog(@"
age = %d
name = %@", human3.age, human3.name);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/iOSCain/p/4017649.html