KVC结合NSCoding实例代码

item.h

1
2
3
4
5
6
7
8
9
10
11
#import <Foundation/Foundation.h>
@interface Item : NSObject
@property (nonatomic, strong) NSString *identifier;
@property (nonatomic, strong) NSString *title;
@property (nonatomic, strong) NSString *notes;
- (id)initWithTitle:(NSString *)title notes:(NSString *)notes;
@end

item.m

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#import "Item.h"
@implementation Item
- (NSArray *)keysForEncoding;
{
return [NSArray arrayWithObjects:@"title", @"notes", @"identifier", nil];
}
- (id)initWithTitle:(NSString *)title notes:(NSString *)notes
{
self = [super init];
if (self)
{
self.title = title;
self.notes = notes;
// create a unique identifier for this object, helps with state restoration
NSUUID *uuid = [[NSUUID alloc] init];
self.identifier = [uuid UUIDString];
}
return self;
}
// we are being created based on what was archived earlier
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super init];
if (self)
{
for (NSString *key in self.keysForEncoding)
{
[self setValue:[aDecoder decodeObjectForKey:key] forKey:key];
}
}
return self;
}
// we are asked to be archived, encode all our data
- (void)encodeWithCoder:(NSCoder *)aCoder
{
for (NSString *key in self.keysForEncoding)
{
[aCoder encodeObject:[self valueForKey:key] forKey:key];
}
}
@end

巧妙的利用KVC辅助实现对象的序列化