序列化: 将数据结构或对象转换成二进制串的过程。这个过程叫做Archiving。二进制流可以通过网络或写入文件中。
反序列化:将在序列化过程中所生成的二进制串转换成数据结构或者对象的过程。即为Unarchiving。
例子:有个类User,分别有三个属性。首先应遵守NSCoding协议,如下图所示。
1.实现协议
1
2
3
4
5
6
7
8
9
10
11
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface User : NSObject<NSCoding>//遵守NSCoding协议
@property (nonatomic,strong)NSString *name;
@property (nonatomic,assign)NSInteger age;
@property (nonatomic,assign)CGPoint location;
@end
实现NSCoding协议方法,即实现编码/解码方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#import "User.h"
@implementation User
//编码
- (void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:_name forKey:@"name"];
[aCoder encodeInteger:_age forKey:@"age"];
[aCoder encodeObject:NSStringFromCGPoint(_location) forKey:@"location"];
}
//解码
- (instancetype)initWithCoder:(NSCoder *)aDecoder{
if (self = [super init]) {
_name = [aDecoder decodeObjectForKey:@"name"];
_age = [aDecoder decodeIntegerForKey:@"age"];
_location = CGPointFromString([aDecoder decodeObjectForKey:@"location"]);
}
return self;
}
@end
2.序列化为二进制数据(转为NSData并存储)
1
2
3
4
5
6
7
8
9
10
11
12
13
User *user = [[User alloc]init];
user.name = @"xiaoming";
user.age = 18;
user.location = CGPointMake(100, 30);
//archive
NSData *data=[NSKeyedArchiver archivedDataWithRootObject:user];
//create path
NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
path = [path stringByAppendingPathComponent:@"user.dat"];
//save
BOOL ret = [data writeToFile:path atomically:YES];
3.反序列化为对象(将NSData转化为对象模型)
1
User *user = [NSKeyedUnarchiver unarchiveObjectWithFile:path];