ios 沙盒 NSCoding 归档 数据存储

转自: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);
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值