-
Notifications
You must be signed in to change notification settings - Fork 0
/
ObjectToDictionary.m
65 lines (56 loc) · 1.85 KB
/
ObjectToDictionary.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
//
// NSDictionary+ObjectToDictionary.m
// AdditionsLib
//
// Created by Guy Shaviv on 30/9/11.
// Copyright (c) 2011 LitePoint Corp. All rights reserved.
//
#import "ObjectToDictionary.h"
@implementation NSDictionary (ObjectToDictionary)
- (id) createObject {
Class objclass = NSClassFromString(self[@"class"]);
if (!objclass) return nil;
NSLog(@"objclas=%@",objclass);
return [[objclass alloc] initWithContentOfDictionary:self];
}
@end
@implementation NSArray (ObjectToDictionary)
- (NSMutableArray*) readArray:(NSArray*)array {
NSMutableArray *collection = [NSMutableArray array];
for (NSDictionary *dict in array) {
id obj = [dict createObject];
if (obj)
[collection addObject:obj];
}
return collection;
}
- (NSArray*) arrayWithDictionaries {
NSMutableArray *array = [NSMutableArray arrayWithCapacity:self.count];
[self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if ([obj respondsToSelector:@selector(contentsTodictionary)]) {
[array addObject:[obj contentsTodictionary]];
}
}];
return array;
}
- (NSDictionary*) contentsTodictionary {
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
dict[@"class"] = NSStringFromClass([self class]);
dict[@"array"] = [self arrayWithDictionaries];
return dict;
}
- (id) initWithContentOfDictionary:(NSDictionary *)dict {
return [NSArray arrayWithArray:[self readArray:dict[@"array"]]];
}
@end
@implementation NSMutableArray (ObjectToDictionary)
- (id) initWithContentOfDictionary:(NSDictionary *)dict {
return [self readArray:dict[@"array"]];
}
- (NSDictionary*) contentsTodictionary {
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
dict[@"class"] = NSStringFromClass([self class]);
dict[@"array"] = [self arrayWithDictionaries];
return dict;
}
@end