博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
简单的归档、接档
阅读量:6687 次
发布时间:2019-06-25

本文共 1628 字,大约阅读时间需要 5 分钟。

#import <Foundation/Foundation.h>

 @interface model : NSObject

@property(nonatomic,copy)NSString *bookName;

@property(nonatomic,assign)double BookPrice;

@end

//实现委托

@interface model()<NSCoding>

@end

@implementation model

//归档

- (void)encodeWithCoder:(NSCoder *)aCoder{

    [aCoder encodeObject:self.bookName forKey:@"BookName"];

    [aCoder encodeDouble:self.BookPrice forKey:@"BookPrice"];

  }

//解档

- (id)initWithCoder:(NSCoder *)aDecoder{

    self=[super init];

    if (self) {

        self.bookName= [aDecoder decodeObjectForKey:@"BookName"];

        self.BookPrice= [aDecoder decodeDoubleForKey:@"BookPrice"];

    }

    return  self;

}

 

 

要使用的内中

  //归档(OC对象->NSData)

    NSMutableData *data = [NSMutableData data];

    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];

    //模型数据

    model *mo=[[model alloc]init];

    mo.bookName=@"APP";

    mo.BookPrice=18.5;

    [archiver encodeObject:mo forKey:@"mo"];

    [archiver finishEncoding];

    //Document路径

    NSString *paths = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingString:@"model.txt"];

    

    if ([data writeToFile:paths atomically:NO]) {

        NSLog(@"写入成功");

    }

    else{

        NSLog(@"写入失败");

    }

}

 

- (void)jied{

    NSString *paths = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingString:@"model.txt"];

    //解档

    NSMutableData *data = [NSMutableData dataWithContentsOfFile:paths];

    

    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];

    

    model *mo = [unarchiver decodeObjectForKey:@"mo"];

    //完成解档

    [unarchiver finishDecoding];

 

转载于:https://www.cnblogs.com/zhuzhushen/p/4226732.html

你可能感兴趣的文章
Confluence 6 升级自定义的站点和空间获得你的自定义布局
查看>>
Angular CLI 创建你的第一个 Angular 示例程序
查看>>
深入理解javascript原型和闭包(16)——完结
查看>>
近日记事2-PG库挂掉了,还是恢复吧~
查看>>
数据源ObjectDataSource的数据访问类的编写
查看>>
如何点击每一列的时候alert其index
查看>>
【原创翻译】类型
查看>>
深入解读Windows Azure VM 实例级 IP
查看>>
python常用函数
查看>>
Eclipse记录
查看>>
C++ 一个自己实现的字符串类
查看>>
KVM
查看>>
我的友情链接
查看>>
字节流
查看>>
大型网站架构演变和知识体系
查看>>
抛砖引玉:Session和Cookie在WEB开发中的最佳实践
查看>>
一次小***处理
查看>>
Nginx配置文件nginx.conf中文详解
查看>>
linux anaconda kickstart基础
查看>>
DITA vs DocBook
查看>>