NSCoding + NSKeyed​Archiver

原创
2014/11/06 21:25
阅读数 68
今天学习学习NSKeyedArchiver的使用。 我们工作中得大多数应用都需要做关于数据持久的功能。iOS中我们可以使用CoreData和NSKeyedArchiver/NSKeyedUnarchiver(用来(反)序列化遵守NSCoding的类)。 如果有建立模型,遍历,查询,以及持久复杂的对象关系的需求时,无可替代的是使用CoreData,虽然说CoreData很强大,但有时候用来做些小事情时,显得有点大材小用,所以需要其他的帮手来完成一些简单的工作,各司其职。 常用的一个就是NSKeyedArchiver。NSCoding是一个简单的协议,包含两个方法,-initWithCoder: 和encodeWithCoder:。必需是遵守这个协议的类才能够又NSKeyedArchiver序列化,否则就会出现unrecognized selector sent to instance。 下面是一个例子
#import <Foundation/Foundation.h>

@interface PeopleModel : NSObject<NSCoding>
@property (strong,nonatomic) NSString* name;
@property (strong,nonatomic) NSString* address;
@property (strong,nonatomic) NSString* phone;
@end
 
#import "PeopleModel.h"

@implementation PeopleModel
-(id)initWithCoder:(NSCoder *)aDecoder{
    self = [super init];
    if(!self)
        return nil;
    self.name = [aDecoder decodeObjectForKey:@"name"];
    self.address = [aDecoder decodeObjectForKey:@"address"];
    self.phone = [aDecoder decodeObjectForKey:@"phone"];

    return self;
}

-(void)encodeWithCoder:(NSCoder *)aCoder{
    [aCoder encodeObject:self.name forKey:@"name"];
    [aCoder encodeObject:self.address forKey:@"address"];
    [aCoder encodeObject:self.phone forKey:@"phone"];
}
@end
序列化:
PeopleModel* people = [PeopleModel new];
people.name = _name.text;
people.address = _address.text;
people.phone = _phone.text;

[NSKeyedArchiver archiveRootObject:people toFile:_dataFilePath];
反序列化
NSArray* dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* docsDir = dirPaths[0];
    _dataFilePath = [docsDir stringByAppendingPathComponent:@"data.archive"];
    NSFileManager* filemgr = [NSFileManager defaultManager];
    if([filemgr fileExistsAtPath:_dataFilePath]){
        PeopleModel* people = [NSKeyedUnarchiver unarchiveObjectWithFile:_dataFilePath];
        _name.text = people.name;
        _address.text = people.address;
        _phone.text = people.phone;
    }
nskeydArchiver
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部