NSCoder&&NSCoding使用

NScoder和NScoding的作用是将自定义的类的对象持久化保存

 

NSCoding 协议

 

这两个方法由系统来调用

 

 

// NSKeyedUnarchiver会把二进制流转化为对象
- initWithCoder // 从coder中读取数据,反序列化数据,实例化一个对象

// NSKeyedArchiver会把对象转化为二进制流
- encodeWithCoder:  // 读取实例变量,把对象序列化,写到coder中

 

 

 

一个简单的例子:

 .h

@interface GKPerson : NSObject <NSCoding>

@property (nonatomic,strong) NSString *firstName;
@property (nonatomic,strong) NSString *lastName;

@end

 .m

#import "GKPerson.h"

@implementation GKPerson

- (instancetype)initWithCoder:(NSCoder *)coder
{
//    self = [super initWithCoder:coder];
    self = [super init];
    if (self) {
        self.firstName = [coder decodeObjectForKey:@"first_name"];
        self.lastName = [coder decodeObjectForKey:@"last_name"];
        
    }
    return self;
}

- (void)encodeWithCoder:(NSCoder *)coder
{
//    [super encodeWithCoder:coder];
    
    [coder encodeObject:self.firstName forKey:@"first_name"];
    [coder encodeObject:self.lastName forKey:@"last_name"];
    
}

@end

 

 把对象持久化保存

    // 把对象保存在本地
    GKPerson *peter = [[GKPerson alloc] init];
    peter.firstName = @"peter";
    peter.lastName = @"nana";
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:peter];
    [[NSUserDefaults standardUserDefaults] setObject:data forKey:@"peter"];

 

 从本地读取对象

    
   NSData *tData = [[NSUserDefaults standardUserDefaults] objectForKey:@"peter"];
    GKPerson *person = [NSKeyedUnarchiver unarchiveObjectWithData:tData];
    
    

 

 

 

你可能感兴趣的:(code)