|
10 | 10 |
|
11 | 11 | #import "JSONAPIResourceLinker.h"
|
12 | 12 |
|
| 13 | +#import <objc/runtime.h> |
| 14 | +#import <objc/message.h> |
| 15 | + |
13 | 16 | #pragma mark - JSONAPIResource
|
14 | 17 |
|
15 | 18 | @interface JSONAPIResource()
|
@@ -176,4 +179,77 @@ - (void)linkLinks:(NSDictionary*)linked {
|
176 | 179 | }
|
177 | 180 | }
|
178 | 181 |
|
| 182 | +#pragma mark - NSCoding |
| 183 | + |
| 184 | +- (NSArray *)propertyKeys |
| 185 | +{ |
| 186 | + NSMutableArray *array = [NSMutableArray array]; |
| 187 | + Class class = [self class]; |
| 188 | + while (class != [NSObject class]) |
| 189 | + { |
| 190 | + unsigned int propertyCount; |
| 191 | + objc_property_t *properties = class_copyPropertyList(class, &propertyCount); |
| 192 | + for (int i = 0; i < propertyCount; i++) |
| 193 | + { |
| 194 | + //get property |
| 195 | + objc_property_t property = properties[i]; |
| 196 | + const char *propertyName = property_getName(property); |
| 197 | + NSString *key = [NSString stringWithCString:propertyName encoding:NSUTF8StringEncoding]; |
| 198 | + |
| 199 | + //check if read-only |
| 200 | + BOOL readonly = NO; |
| 201 | + const char *attributes = property_getAttributes(property); |
| 202 | + NSString *encoding = [NSString stringWithCString:attributes encoding:NSUTF8StringEncoding]; |
| 203 | + if ([[encoding componentsSeparatedByString:@","] containsObject:@"R"]) |
| 204 | + { |
| 205 | + readonly = YES; |
| 206 | + |
| 207 | + //see if there is a backing ivar with a KVC-compliant name |
| 208 | + NSRange iVarRange = [encoding rangeOfString:@",V"]; |
| 209 | + if (iVarRange.location != NSNotFound) |
| 210 | + { |
| 211 | + NSString *iVarName = [encoding substringFromIndex:iVarRange.location + 2]; |
| 212 | + if ([iVarName isEqualToString:key] || |
| 213 | + [iVarName isEqualToString:[@"_" stringByAppendingString:key]]) |
| 214 | + { |
| 215 | + //setValue:forKey: will still work |
| 216 | + readonly = NO; |
| 217 | + } |
| 218 | + } |
| 219 | + } |
| 220 | + |
| 221 | + if (!readonly) |
| 222 | + { |
| 223 | + //exclude read-only properties |
| 224 | + [array addObject:key]; |
| 225 | + } |
| 226 | + } |
| 227 | + free(properties); |
| 228 | + class = [class superclass]; |
| 229 | + } |
| 230 | + return array; |
| 231 | +} |
| 232 | + |
| 233 | +- (id)initWithCoder:(NSCoder *)aDecoder |
| 234 | +{ |
| 235 | + if ((self = [self init])) |
| 236 | + { |
| 237 | + for (NSString *key in [self propertyKeys]) |
| 238 | + { |
| 239 | + id value = [aDecoder decodeObjectForKey:key]; |
| 240 | + [self setValue:value forKey:key]; |
| 241 | + } |
| 242 | + } |
| 243 | + return self; |
| 244 | +} |
| 245 | + |
| 246 | +- (void)encodeWithCoder:(NSCoder *)aCoder |
| 247 | +{ |
| 248 | + for (NSString *key in [self propertyKeys]) |
| 249 | + { |
| 250 | + id value = [self valueForKey:key]; |
| 251 | + [aCoder encodeObject:value forKey:key]; |
| 252 | + } |
| 253 | +} |
| 254 | + |
179 | 255 | @end
|
0 commit comments