-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathNSObject+PropertyReflection.m
71 lines (54 loc) · 1.77 KB
/
NSObject+PropertyReflection.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
//
// NSObject+PropertyReflection.m
// util
//
// Created by mrnuku on 28/05/16.
//
//
#import "NSObject+PropertyReflection.h"
#import "objc/runtime.h"
@implementation NSObject (PropertyReflection)
+ (NSArray *)listPropertyNames:(BOOL)excludeReadOnly {
unsigned int outCount = 0;
objc_property_t *properties = class_copyPropertyList(self.class, &outCount);
NSMutableArray<NSString *> *result = [NSMutableArray arrayWithCapacity:outCount];
for (unsigned int i = 0; i < outCount; i++) {
objc_property_t property = properties[i];
const char *propName = property_getName(property);
if (!propName) {
continue;
}
if (!excludeReadOnly || ![[@(property_getAttributes(property)) componentsSeparatedByString:@","] containsObject:@"R"]) {
[result addObject:@(propName)];
}
}
free(properties);
return result.copy;
}
- (id)reflectedCopy {
id object = [self.class new];
NSArray *properties = [self.class listPropertyNames:YES];
for (NSString *key in properties) {
id value = [self valueForKey:key];
if (value) {
[object setValue:value forKey:key];
}
}
return object;
}
- (NSString *)reflectedDescription {
NSArray<NSString *> *properties = [self.class listPropertyNames:NO];
NSMutableString *desc = [NSMutableString new];
for (NSString *propertyName in properties) {
id value = [self valueForKey:propertyName];
if (value) {
if (desc.length) {
[desc appendString:@", "];
}
[desc appendString:propertyName];
[desc appendFormat:@": \"%@\"", value];
}
}
return desc.copy;
}
@end