ios 沙盒 NSCoding 归档 数据存储

时间:2022-01-30 22:12:18

转自:http://www.maxiaoguo.com/clothes/232.html


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

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

NSKeyedUnarchiver unarchiveObjectWithFile:path 读取

对象代码

#import <Foundation/Foundation.h>

@interface MJStudent : NSObject  <NSCoding>
@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);
}