-
Notifications
You must be signed in to change notification settings - Fork 106
/
Copy pathNSObject+Properties.m
101 lines (67 loc) · 2.77 KB
/
NSObject+Properties.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
96
97
98
99
100
101
//
// NSObject+Properties.m
// AutoNSObjectDescription
//
// Created by wpstarnice on 2017/2/22.
// Copyright © 2017年 p. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
#import "ViewController.h"
@implementation NSObject (Properties)
static NSMutableDictionary *ClassDescriptionCacheMap;
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
ClassDescriptionCacheMap = [NSMutableDictionary dictionary];
});
}
/**
because custom class not implements '- (NSString *)description' ,so '- (NSString *)description' of this custom category will be first transversed,
as contrast,
'- (NSString *)description' of system class or its category is always loaded before custom category by developer,so the system api,'- (NSString *)description',will be first transversed
*/
- (NSString *)description {
NSString *des = [ClassDescriptionCacheMap objectForKey:[self class]];
if (nil == des){
NSMutableString *string = [NSMutableString string];
[string appendString:NSStringFromClass([self class])];
[string appendString:@"{\n"];
NSDictionary *propertydic = [self dictionaryWithProperties];
[propertydic enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
[string appendFormat:@"%@ = %@\n", key, obj];
}];
[string appendString:@"}"];
des = string;
NSString *className = NSStringFromClass([self class]);
[ClassDescriptionCacheMap setValue:des forKey:className];
}
return des;
}
#pragma mark - dictionary : ivar - value
/**
class_copyIvarList 和 class_copyPropertyList 区别为后者只获得属性,而前者属性和变量都会获得
*/
- (NSDictionary *)dictionaryWithProperties {
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
unsigned int ivarsCount = 0;
Ivar *ivars = class_copyIvarList([self class], &ivarsCount);
for (unsigned int i = 0 ; i<ivarsCount ; i++) {
NSString *propertyName = [NSString stringWithUTF8String:ivar_getName(ivars[i])];
//属性名字前面会有@"_"
propertyName = [propertyName hasPrefix:@"-"] ? [propertyName substringFromIndex:1] : propertyName;
id value = [self valueForKey:propertyName];
[dictionary setObject:value ? value : @"" forKey:propertyName];
}
return dictionary;
}
#pragma mark -
- (BOOL)isSystemClass {
NSBundle *bundle = [NSBundle bundleForClass:[self class]];
if ([bundle isEqual: [NSBundle mainBundle]]) {
NSLog(@"Custom class");
return NO;
}
return YES;
}
@end