NSCoding的使用方法---Mac上的归档.

NSCoding是什么?

NSCoding就是我们俗称的归档, 归档的意思就是把工程里的某一段对象的代码以文件的方式储存起来, 在这里分别有两种归档方式, 一中是在Mac上的归档, 一种是iOS上的归档, 今天这里只介绍在Mac上的归档.

这里涉及的方法.

NSData

NSKeyedArchiver archivedDataWithRootObject:这个方法的意思就是把某一个对象以二进制的形式储存起来.

writeToFileatomically:这个方法的意思就是, 存储的路径以及是否存储.

 

下面是一个简单的例子:

首先我们要创建一个新的类, 这里我们需要注意一个东西, 新创建的类继承与NSObject, 但同时要实现NSCoding的协议.

#import <Foundation/Foundation.h>

@interface Human : NSObject <NSCoding>
{
@private
    int _age;
    NSString *_name;
    Human *_child;
}

@property (nonatomic, assign)int age;
@property (nonatomic, copy)NSString *name;
@property (nonatomic, retain)Human *child;

@end

实现NSCoding协议里的方法.

#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"];
        self.name = [aDecoder decodeObjectForKey:@"_name"];
        self.child = [aDecoder decodeObjectForKey:@"_child"];
    }
    return self;
}
@end

在主函数初始化要归档的对象和参数.

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

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        
        Human *human1 = [[Human alloc]init];
        Human *human2 = [[Human alloc]init];
        
        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];
        NSLog(@"%@",data1);
  }
  return 0;
}
原文地址:https://www.cnblogs.com/iOSCain/p/4034972.html