对模型对象进行归档

 

只有在类中实现的每个属性都都时量标(如int或float) 或都是遵循NSCoding协议的某个类的实例,就可以对整个对象进行完全归档

1.遵循NSCoding协议

--------------------

编码

- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:foo forKey:kFooKey];
    [aCoder encodeObject:bar forKey:kBarKey];
    [aCoder encodeInt:someInt forKey:kSomeIntKey];
    [aCoder encodeFloat:someFloat forKey:kSomeFloatKey];
}

如果要子类化某个也遵循NSCoding的类,还需要确保对超类调用encodeWithCoder:

[super encodeWithCoder:aCode];加在程序最开头

---------------------------
解码

- (id)initWithCoder:(NSCoder *)aDecoder
{
    if (self = [super init]) {
        foo = [aDecoder decodeObjectForKey:kFooKey];
        bar = [aDecoder decodeObjectForKey:kBarKey];
        someInt = [aDecoder decodeIntForKey:kSomeIntKey];
        someFloat = [aDecoder decodeFloatForKey:kSomeFloat];
    }
}

当为某个具有超类且遵循NSCoding的类实现NSCoding时,不再调用super的init方法,而是调用initWithCoder:

if (self = [super initWithCoder:aDecoder])


2.实现NSCopying协议

- (id)copyWithZone:(NSZone *)zone
{
    MyClass *copy = [[[self class] allocWithZone:zone]init];
    copy.foo = [self.foo copyWithZone:zone];
    copy.bar = [self.bar copyWithZone:zone];
    copy.someInt = self.someInt;
    copy.someFloat = self.someFloat;
    return copy;
}

3.对数据对象进行归档和取消归档

归档

    NSMutableData *data = [[NSMutableData alloc] init];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    [archiver encodeObject:myObject forKey:@"keyValueString"];
    [archiver finishEncoding];
    BOOL success = [data writeToFile:@"/path/to/archive" atomically:YES];
写入文件错误success为NO


从归档重组对象步骤

    NSData *data = [[NSData alloc] initWithContentsOfFile:@"/path/to/archive"];
    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
    self.object = [unarchiver decodeObjectForKey:@"keyValueString"];
    [unarchiver finishDecoding];


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值