zoukankan      html  css  js  c++  java
  • OC-多个自定义对象的归档与解归档

    对于上一章节,简单讲述了一个自定义对象的归档与解归档:http://www.cnblogs.com/BeyondAverage0908/p/4597245.html

    本章节阐述下多个自定义对象的归档与解归档

    以下代码阐述:定义了两个类Dog和Cat,并且利用@property展开了对应的几个属性(简单的代码,不贴源码了)。

    以下代码部分位主要的归档与解归档代码:注意需要在对应的自定义类中实现以下两个方法:- (void)encodeWithCoder:(NSCoder *)aCoder;方法,- (id)initWithCoder:(NSCoder *)aDecoder;     具体的实现详情见上一篇博客内容

    #import "Dog.h"
    #import "Cat.h"
    
    int main(int argc, const char * argv[]) {
        @autoreleasepool {
            //定义Dog对象
            Dog *xiaohei = [[Dog alloc] init];
            xiaohei.name = @"小黑";
            xiaohei.age = 12;
            
            Cat *xiaomao = [[Cat alloc] init];
            xiaomao.name = @"小猫";
            xiaomao.nickname = @"阿花";
            xiaomao.weight = 2.03;
            
            //归档
            //定义一个可变数据对象(必须),在编码的时候存储自定义对象
            NSMutableData *mutDate = [NSMutableData data];
            NSKeyedArchiver *keyedArch = [[NSKeyedArchiver alloc] initForWritingWithMutableData:mutDate];
            //对 dog 和 cat 进行格式编码
            [keyedArch encodeObject:xiaohei forKey:@"xiaohei"];
            [keyedArch encodeObject:xiaomao forKey:@"xiaomao"];
            //结束编码
            [keyedArch finishEncoding];
            
            BOOL flag = [mutDate writeToFile:@"/Users/qianfeng/Desktop/day22_OC12_协议/day22_OC12_自定义对象归档与解归档/dogandcat.txt" atomically:YES];
            if (flag) {
                NSLog(@"多个自定义对象归档成功");
            }else{
                NSLog(@"多个自定义对象归档失败");
            }
            
            
            //解归档:将归档后的文件中的对象读取出来
            NSData *data = [NSData dataWithContentsOfFile:@"/Users/qianfeng/Desktop/day22_OC12_协议/day22_OC12_自定义对象归档与解归档/dogandcat.txt"];
            NSKeyedUnarchiver *keyedUnarch = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
            Dog *nDog = [keyedUnarch decodeObjectForKey:@"xiaohei"];
            Cat *nCat = [keyedUnarch decodeObjectForKey:@"xiaomao"];
            [keyedUnarch finishDecoding];
            NSLog(@"nDog = %@",nDog);
            NSLog(@"nCat name = %@,nickname = %@,weight = %.2f",nCat.name,nCat.nickname,nCat.weight);
        }
        return 0;
    }
  • 相关阅读:
    负数求余数 C 和 Matlab&Python 处理不一样
    [Matlab] 线性卷积&圆周卷积代码实现
    [Arduino] 驱动RC522 读取 UID例程
    [C++] Nested Radical Constant
    [Arduino] 学习总结小合集(更新ING)
    谐振电路的品质因素总结
    142. Linked List Cycle II
    664. Strange Printer
    188. Best Time to Buy and Sell Stock IV
    50. Pow(x, n)
  • 原文地址:https://www.cnblogs.com/BeyondAverage0908/p/4597406.html
Copyright © 2011-2022 走看看