IOS学习笔记二十三对象归档(NSKeyedArchiver、NSKeyedUnArchiver、NSCodeing)

本文介绍了iOS中对象持久化的方法,主要讲解了NSKeyedArchiver和NSCoding协议的使用。通过archiveRootObject:toFile:和unarchiveObjectWithFile:进行对象的存档和恢复。同时,详细阐述了NSCoding协议的initWithCoder:和encodeWithCoder:方法。并提供了一个IApple对象的归档和解档示例代码,展示了如何将Dictionary和普通对象进行对象归档。

1、NSKeyedArchiver、NSKeyedUnArchiver

1)、archiveRootObject:toFile 归档对象到这个路径文件

2)、unarchiveObjectWithFile:从这个路径文件把对象进行恢复

对象归档这里我们可以理解Android里面的序列化,就是把对象保存到文件持久化,Android里面进行持久化的必须实现Serializable和Parcelable,然后IOS里面持久化必须实现NSCodeing协议,IOS进行持久化操作一般需要NSKeyedArchiver实现。
 
2、NSCodeing协议

1)、initWithCoder:该方法恢复对象

2)、encodeWithCoder:归档该对象

 
3、测试Demo(把Dictionary和普通对象进行对象归档)

IApple.h

    #import <Foundation/Foundation.h>
    #ifndef IApple_h
    #define IApple_h
    @interface IApple : NSObject <NSCoding>
    @property (nonatomic, copy) NSString *color;
    @property (nonatomic, assign) double weight;
    @property (nonatomic, assign) int size;
    -(id)initWithColor:(NSString *) color weight:(double) weight size:(int) size;
    @end
     
    #endif /* IApple_h */


IApple.m

    #import  "IApple.h"
    #import <Foundation/Foundation.h>
    @implementation IApple
    @synthesize color = _color;
    @synthesize weight = _weight;
    @synthesize size = _size;
    -(id)initWithColor:(NSString *) color weight:(double) weight size:(int) size
    {
        if (self = [super init])
        {
            self.color = color;
            self.weight = weight;
            self.size = size;
        }
        return self;
    }
    -(NSString *)description
    {
        return [NSString stringWithFormat:@"<IApple [color = %@, weight = %g, _size = %d]>", self.color, self.weight, self.size];
    }
     
    -(void)encodeWithCoder:(NSCoder *)aCoder
    {
        [aCoder encodeObject:_color forKey:@"color"];
        [aCoder encodeDouble:_weight forKey:@"weight"];
        [aCoder encodeInt:_size forKey:@"size"];
    }
    -(id) initWithCoder:(NSCoder *)aDecoder
    {
        _color = [aDecoder decodeObjectForKey:@"color"];
        _weight = [aDecoder decodeDoubleForKey:@"weight"];
        _size = [aDecoder decodeIntForKey:@"size"];
        return self;

更多请见:http://www.mark-to-win.com/tutorial/52000.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值