ios 沙盒 NSCoding(相当于JAVA对象序列化) 归档 数据存储

通过NSCoding能实现像JAVA一样能够实现对象的序列化,可以保存对象到文件里。

NSCoding 跟其他存储方式略有不同,他可以存储对象

对象存储的条件是: 对象需要遵守 NSCoding 协议
存储的时候需要 调用 encodeWithCoder 方法
读取的时候需要调用initWithCoder 方法
[NSKeyedArchiver archiveRootObject:stu toFile:path]; 存储

NSKeyedUnarchiver unarchiveObjectWithFile:path 读取

对象代码

  1. #import <Foundation/Foundation.h>
  2. @interface MJStudent : NSObject  <NSCoding>
  3. @property (nonatomic, copy) NSString *no;
  4. @property (nonatomic, assign) double height;
  5. @property (nonatomic, assign) int age;
  6. @end
  1. #import "MJStudent.h"
  2. @interface MJStudent()
  3. @end
  4. @implementation MJStudent
  5. /**
  6. *  将某个对象写入文件时会调用
  7. *  在这个方法中说清楚哪些属性需要存储
  8. */
  9. - (void)encodeWithCoder:(NSCoder *)encoder
  10. {
  11. [encoder encodeObject:self.no forKey:@"no"];
  12. [encoder encodeInt:self.age forKey:@"age"];
  13. [encoder encodeDouble:self.height forKey:@"height"];
  14. }
  15. /**
  16. *  从文件中解析对象时会调用
  17. *  在这个方法中说清楚哪些属性需要存储
  18. */
  19. - (id)initWithCoder:(NSCoder *)decoder
  20. {
  21. if (self = [super init]) {
  22. // 读取文件的内容
  23. self.no = [decoder decodeObjectForKey:@"no"];
  24. self.age = [decoder decodeIntForKey:@"age"];
  25. self.height = [decoder decodeDoubleForKey:@"height"];
  26. }
  27. return self;
  28. }
  29. @end

保存读取

    1. - (IBAction)save {
    2. // 1.新的模型对象
    3. MJStudent *stu = [[MJStudent alloc] init];
    4. stu.no = @"42343254";
    5. stu.age = 20;
    6. stu.height = 1.55;
    7. // 2.归档模型对象
    8. // 2.1.获得Documents的全路径
    9. NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    10. // 2.2.获得文件的全路径
    11. NSString *path = [doc stringByAppendingPathComponent:@"stu.data"];
    12. // 2.3.将对象归档
    13. [NSKeyedArchiver archiveRootObject:stu toFile:path];
    14. }
    15. - (IBAction)read {
    16. // 1.获得Documents的全路径
    17. NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    18. // 2.获得文件的全路径
    19. NSString *path = [doc stringByAppendingPathComponent:@"stu.data"];
    20. // 3.从文件中读取MJStudent对象
    21. MJStudent *stu = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
    22. NSLog(@"%@ %d %f", stu.no, stu.age, stu.height);
    23. }
上一篇:virtual 修饰符与继承对析构函数的影响(C++)


下一篇:Unity插件之NGUI学习(5)—— 创建Label图文混排及文字点击