forked from Kapeli/Dash-iOS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAutoCoding.m
More file actions
275 lines (249 loc) · 9.04 KB
/
AutoCoding.m
File metadata and controls
275 lines (249 loc) · 9.04 KB
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
//
// AutoCoding.m
//
// Version 2.2.2
//
// Created by Nick Lockwood on 19/11/2011.
// Copyright (c) 2011 Charcoal Design
//
// Distributed under the permissive zlib License
// Get the latest version from here:
//
// https://github.com/nicklockwood/AutoCoding
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
#import "AutoCoding.h"
#import <objc/runtime.h>
#pragma clang diagnostic ignored "-Wgnu"
#pragma clang diagnostic ignored "-Wpartial-availability"
#pragma clang diagnostic ignored "-Wobjc-designated-initializers"
static NSString *const AutocodingException = @"AutocodingException";
@implementation NSObject (AutoCoding)
+ (BOOL)supportsSecureCoding
{
return YES;
}
+ (instancetype)objectWithContentsOfFile:(NSString *)filePath
{
//load the file
NSData *data = [NSData dataWithContentsOfFile:filePath];
//attempt to deserialise data as a plist
id object = nil;
if (data)
{
NSPropertyListFormat format;
object = [NSPropertyListSerialization propertyListWithData:data options:NSPropertyListImmutable format:&format error:NULL];
//success?
if (object)
{
//check if object is an NSCoded unarchive
if ([object respondsToSelector:@selector(objectForKeyedSubscript:)] && ((NSDictionary *)object)[@"$archiver"])
{
object = [NSKeyedUnarchiver unarchiveObjectWithData:data];
}
}
else
{
//return raw data
object = data;
}
}
//return object
return object;
}
- (BOOL)writeToFile:(NSString *)filePath atomically:(BOOL)useAuxiliaryFile
{
//note: NSData, NSDictionary and NSArray already implement this method
//and do not save using NSCoding, however the objectWithContentsOfFile
//method will correctly recover these objects anyway
//archive object
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:self];
return [data writeToFile:filePath atomically:useAuxiliaryFile];
}
+ (NSDictionary<NSString *, Class> *)codableProperties
{
//deprecated
SEL deprecatedSelector = NSSelectorFromString(@"uncodableProperties");
NSArray *uncodableProperties = nil;
if ([self respondsToSelector:deprecatedSelector] || [self instancesRespondToSelector:deprecatedSelector])
{
uncodableProperties = [self valueForKey:@"uncodableProperties"];
NSLog(@"AutoCoding Warning: uncodableProperties method is no longer supported. Use ivars, or synthesize your properties using non-KVC-compliant names to avoid coding them instead.");
}
unsigned int propertyCount;
__autoreleasing NSMutableDictionary *codableProperties = [NSMutableDictionary dictionary];
objc_property_t *properties = class_copyPropertyList(self, &propertyCount);
for (unsigned int i = 0; i < propertyCount; i++)
{
//get property name
objc_property_t property = properties[i];
const char *propertyName = property_getName(property);
__autoreleasing NSString *key = @(propertyName);
//check if codable
if (![uncodableProperties containsObject:key])
{
//get property type
Class propertyClass = nil;
char *typeEncoding = property_copyAttributeValue(property, "T");
switch (typeEncoding[0])
{
case '@':
{
if (strlen(typeEncoding) >= 3)
{
char *className = strndup(typeEncoding + 2, strlen(typeEncoding) - 3);
__autoreleasing NSString *name = @(className);
NSRange range = [name rangeOfString:@"<"];
if (range.location != NSNotFound)
{
name = [name substringToIndex:range.location];
}
propertyClass = NSClassFromString(name) ?: [NSObject class];
free(className);
}
break;
}
case 'c':
case 'i':
case 's':
case 'l':
case 'q':
case 'C':
case 'I':
case 'S':
case 'L':
case 'Q':
case 'f':
case 'd':
case 'B':
{
propertyClass = [NSNumber class];
break;
}
case '{':
{
propertyClass = [NSValue class];
break;
}
}
free(typeEncoding);
if (propertyClass)
{
//check if there is a backing ivar
char *ivar = property_copyAttributeValue(property, "V");
if (ivar)
{
//check if ivar has KVC-compliant name
__autoreleasing NSString *ivarName = @(ivar);
if ([ivarName isEqualToString:key] || [ivarName isEqualToString:[@"_" stringByAppendingString:key]])
{
//no setter, but setValue:forKey: will still work
codableProperties[key] = propertyClass;
}
free(ivar);
}
else
{
//check if property is dynamic and readwrite
char *dynamic = property_copyAttributeValue(property, "D");
char *readonly = property_copyAttributeValue(property, "R");
if (dynamic && !readonly)
{
//no ivar, but setValue:forKey: will still work
codableProperties[key] = propertyClass;
}
free(dynamic);
free(readonly);
}
}
}
}
free(properties);
return codableProperties;
}
- (NSDictionary<NSString *, Class> *)codableProperties
{
__autoreleasing NSDictionary *codableProperties = objc_getAssociatedObject([self class], _cmd);
if (!codableProperties)
{
codableProperties = [NSMutableDictionary dictionary];
Class subclass = [self class];
while (subclass != [NSObject class])
{
[(NSMutableDictionary *)codableProperties addEntriesFromDictionary:[subclass codableProperties]];
subclass = [subclass superclass];
}
codableProperties = [NSDictionary dictionaryWithDictionary:codableProperties];
//make the association atomically so that we don't need to bother with an @synchronize
objc_setAssociatedObject([self class], _cmd, codableProperties, OBJC_ASSOCIATION_RETAIN);
}
return codableProperties;
}
- (NSDictionary<NSString *, id> *)dictionaryRepresentation
{
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
for (__unsafe_unretained NSString *key in self.codableProperties)
{
id value = [self valueForKey:key];
if (value) dict[key] = value;
}
return dict;
}
- (void)setWithCoder:(NSCoder *)aDecoder
{
BOOL secureAvailable = [aDecoder respondsToSelector:@selector(decodeObjectOfClass:forKey:)];
BOOL secureSupported = [[self class] supportsSecureCoding];
NSDictionary *properties = self.codableProperties;
for (NSString *key in properties)
{
id object = nil;
Class propertyClass = properties[key];
if (secureAvailable)
{
object = [aDecoder decodeObjectOfClass:propertyClass forKey:key];
}
else
{
object = [aDecoder decodeObjectForKey:key];
}
if (object)
{
if (secureSupported && ![object isKindOfClass:propertyClass] && object != [NSNull null])
{
[NSException raise:AutocodingException format:@"Expected '%@' to be a %@, but was actually a %@", key, propertyClass, [object class]];
}
[self setValue:object forKey:key];
}
}
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
[self setWithCoder:aDecoder];
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder
{
for (NSString *key in self.codableProperties)
{
id object = [self valueForKey:key];
if (object) [aCoder encodeObject:object forKey:key];
}
}
@end