-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathKSPropertyListEncoder.m
95 lines (78 loc) · 2.41 KB
/
KSPropertyListEncoder.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
//
// KSPropertyListEncoder.m
// Sandvox
//
// Created by Mike on 10/02/2011.
// Copyright 2011 Karelia Software. All rights reserved.
//
#import "KSPropertyListEncoder.h"
@implementation KSPropertyListEncoder
- (BOOL)allowsKeyedCoding; { return YES; }
#pragma mark Stack
/* Maintain a stack of mutable dictionaries and arrays, that corresponds to the current object being encoded
*/
- (void)pushPropertyList:(id)object forKey:(NSString *)key;
{
if (key)
{
[(NSMutableDictionary *)[_objects lastObject] setObject:object forKey:key];
}
else
{
[(NSMutableArray *)[_objects lastObject] addObject:object];
}
[_objects addObject:object];
}
- (void)popPropertyList;
{
if ([_objects count] > 1) [_objects removeLastObject];
}
#pragma mark Encoding
- (void)encodeObject:(id)objv forKey:(NSString *)key
{
// Nil needs its own simple behaviour
if (!objv)
{
[[_objects lastObject] removeObjectForKey:key];
}
// Arrays get special treatment to avoid recursing through them checking plist-compatibility
else if ([objv isKindOfClass:[NSArray class]])
{
[self pushPropertyList:[NSMutableArray arrayWithCapacity:[objv count]] forKey:key];
for (id anObject in objv)
{
[self encodeObject:anObject forKey:nil];
}
[self popPropertyList];
}
// Dictionaries are already most of the way there
else if ([objv isKindOfClass:[NSDictionary class]])
{
[self pushPropertyList:[NSMutableDictionary dictionary] forKey:key];
for (NSString *aKey in objv)
{
[self encodeObject:[objv objectForKey:aKey] forKey:aKey];
}
[self popPropertyList];
}
// Native, simple plist objects archive themselves
else if ([NSPropertyListSerialization propertyList:objv isValidForFormat:NSPropertyListXMLFormat_v1_0])
{
[[_objects lastObject] setObject:objv forKey:key];
}
// Everything else is turned into a dictionary
else
{
[self pushPropertyList:[NSMutableDictionary dictionary] forKey:key];
[objv encodeWithCoder:self];
[self popPropertyList];
}
}
- (void)encodeRootObject:(id)rootObject;
{
// Reset the stack and go!
[_objects release]; _objects = [[NSMutableArray alloc] init];
[self encodeObject:rootObject forKey:nil];
}
- (id)rootPropertyList; { return [_objects objectAtIndex:0]; }
@end