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

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

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

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

NSKeyedUnarchiver unarchiveObjectWithFile:path 读取

对象代码

[objc] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. #import <Foundation/Foundation.h>  
  2.   
  3. @interface MJStudent : NSObject  <NSCoding>  
  4. @property (nonatomic, copy) NSString *no;  
  5. @property (nonatomic, assign) double height;  
  6. @property (nonatomic, assign) int age;  
  7. @end  



[objc] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. #import "MJStudent.h"  
  2. @interface MJStudent()   
  3. @end  
  4. @implementation MJStudent  
  5.   
  6. /** 
  7.  *  将某个对象写入文件时会调用 
  8.  *  在这个方法中说清楚哪些属性需要存储 
  9.  */  
  10. - (void)encodeWithCoder:(NSCoder *)encoder  
  11. {  
  12.     [encoder encodeObject:self.no forKey:@"no"];  
  13.     [encoder encodeInt:self.age forKey:@"age"];  
  14.     [encoder encodeDouble:self.height forKey:@"height"];  
  15. }  
  16.   
  17. /** 
  18.  *  从文件中解析对象时会调用 
  19.  *  在这个方法中说清楚哪些属性需要存储 
  20.  */  
  21. - (id)initWithCoder:(NSCoder *)decoder  
  22. {  
  23.     if (self = [super init]) {  
  24.         // 读取文件的内容  
  25.         self.no = [decoder decodeObjectForKey:@"no"];  
  26.         self.age = [decoder decodeIntForKey:@"age"];  
  27.         self.height = [decoder decodeDoubleForKey:@"height"];  
  28.     }  
  29.     return self;  
  30. }  
  31. @end  



保存读取

[objc] view plaincopy在CODE上查看代码片派生到我的代码片
 
    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.       
    8.     // 2.归档模型对象  
    9.     // 2.1.获得Documents的全路径  
    10.     NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];  
    11.     // 2.2.获得文件的全路径  
    12.     NSString *path = [doc stringByAppendingPathComponent:@"stu.data"];  
    13.     // 2.3.将对象归档  
    14.     [NSKeyedArchiver archiveRootObject:stu toFile:path];  
    15. }  
    16.   
    17. - (IBAction)read {  
    18.     // 1.获得Documents的全路径  
    19.     NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];  
    20.     // 2.获得文件的全路径  
    21.     NSString *path = [doc stringByAppendingPathComponent:@"stu.data"];  
    22.       
    23.     // 3.从文件中读取MJStudent对象  
    24.     MJStudent *stu = [NSKeyedUnarchiver unarchiveObjectWithFile:path];  
    25.       
    26.     NSLog(@"%@ %d %f", stu.no, stu.age, stu.height);  
    27. }  
原文地址:https://www.cnblogs.com/kenshinobiy/p/4819268.html