博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
iOS 沙盒 NSCoding 归档 数据存储
阅读量:7229 次
发布时间:2019-06-29

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

hot3.png

#import 
    @interface MJStudent : NSObject  
  @property (nonatomic, copy) NSString *no;  @property (nonatomic, assign) double height;  @property (nonatomic, assign) int age;  @end
#import "MJStudent.h"  @interface MJStudent()   @end  @implementation MJStudent    /**  *  将某个对象写入文件时会调用  *  在这个方法中说清楚哪些属性需要存储  */  - (void)encodeWithCoder:(NSCoder *)encoder  {      [encoder encodeObject:self.no forKey:@"no"];      [encoder encodeInt:self.age forKey:@"age"];      [encoder encodeDouble:self.height forKey:@"height"];  }    /**  *  从文件中解析对象时会调用  *  在这个方法中说清楚哪些属性需要存储  */  - (id)initWithCoder:(NSCoder *)decoder  {      if (self = [super init]) {          // 读取文件的内容          self.no = [decoder decodeObjectForKey:@"no"];          self.age = [decoder decodeIntForKey:@"age"];          self.height = [decoder decodeDoubleForKey:@"height"];      }      return self;  }  @end
- (IBAction)save {      // 1.新的模型对象      MJStudent *stu = [[MJStudent alloc] init];      stu.no = @"42343254";      stu.age = 20;      stu.height = 1.55;            // 2.归档模型对象      // 2.1.获得Documents的全路径      NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];      // 2.2.获得文件的全路径      NSString *path = [doc stringByAppendingPathComponent:@"stu.data"];      // 2.3.将对象归档      [NSKeyedArchiver archiveRootObject:stu toFile:path];  }    - (IBAction)read {      // 1.获得Documents的全路径      NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];      // 2.获得文件的全路径      NSString *path = [doc stringByAppendingPathComponent:@"stu.data"];            // 3.从文件中读取MJStudent对象      MJStudent *stu = [NSKeyedUnarchiver unarchiveObjectWithFile:path];            NSLog(@"%@ %d %f", stu.no, stu.age, stu.height);  }

 

转载于:https://my.oschina.net/ososchina/blog/668645

你可能感兴趣的文章
Easy Scheduler 1.0.3 发布,分布式工作流任务调度系统
查看>>
java 颠倒整数
查看>>
Python入门教程100天:Day05-练习总结
查看>>
环境搭建,8种基本类型,Static,package和import,log4j
查看>>
即将到来的 Debian 10 Buster 发布版的新特点
查看>>
iOS 头部视图下拉变大
查看>>
Disruptor并发框架
查看>>
react-hooks 实现简单的评论list
查看>>
【多图警告】学会JavaScript测试你就是同行中最亮的仔(妹)
查看>>
19-04-25
查看>>
一个JAVA程序员成长之路分享
查看>>
30K iOS程序员的简述:如何快速进阶成为高级开发人员
查看>>
Go 夜读 - 每周四晚上 Go 源码阅读技术分享
查看>>
tranform知多少
查看>>
Android电量优化
查看>>
[爬虫手记] 我是如何在3分钟内开发完一个爬虫的
查看>>
【译】Css Grid VS Flexbox: 实践比较
查看>>
iOS 开发知识索引
查看>>
Linux iptables命令
查看>>
webpack的使用
查看>>