在開發(fā)過程中會經(jīng)常通過description方法輸出model的所有屬性和屬性值來查看model是否正確賦值骏令。LBYDescription 庫可以簡單的通過一行代碼獲取到對象的所有屬性以及屬性值抒抬。
LBYDescription 使用姿勢:
導(dǎo)入方式:
- 方式一:直接將NSObject+LBYDescription.h和NSObject+LBYDescription.m拖到項(xiàng)目中匪燕。
- 方式二:通過pod庫導(dǎo)入。
pod 'LBYDescription', '~> 1.0.0'
使用流程:
第一步:import頭文件
#import "NSObject+LBYDescription.h"
第二步:在description方法中執(zhí)行代碼return [self memberDescription];
- (NSString *)description {
return [self memberDescription];
}
memberDescription方法源碼
- (NSString *)memberDescription {
Class klass = self.class;
NSMutableString *propertyInfo = [NSMutableString stringWithFormat:@"====================================================================================================\n%@:\n", NSStringFromClass(klass)];
unsigned int propertyCount = 0;
objc_property_t *properties = class_copyPropertyList(klass, &propertyCount);
if (properties) {
for (unsigned int i = 0; i < propertyCount; i++) {
NSString *name = [self propertyName:properties[i]];
if ([name isKindOfClass:[NSString class]] && name.length) {
id value = [self valueForKey:name];
if (value && value != (id)kCFNull) {
const char *type = property_getAttributes(properties[i]);
type++;
if (*type == 'c' || *type == 'C') { // char / unsigned char
char c;
[value getValue:&c];
[propertyInfo appendFormat:@"%@ = %c;\n", name, c];
} else if (strstr(type, @encode(CATransform3D)) != NULL) { // CATransform3D使用valueForKey取值會得到hex
CATransform3D transform3D;
[value getValue:&transform3D];
[propertyInfo appendFormat:@"%@ = CATransform3D: {%f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f};\n", name, transform3D.m11, transform3D.m12, transform3D.m13, transform3D.m14, transform3D.m21, transform3D.m22, transform3D.m23, transform3D.m24, transform3D.m31, transform3D.m32, transform3D.m33, transform3D.m34, transform3D.m41, transform3D.m42, transform3D.m43, transform3D.m44];
} else if (strstr(type, @encode(CGVector)) != NULL) { // CGVector使用valueForKey取值會得到hex
CGVector vector;
[value getValue:&vector];
[propertyInfo appendFormat:@"%@ = CGVector: {%f, %f};\n", name, vector.dx, vector.dy];
} else {
[propertyInfo appendFormat:@"%@ = %@;\n", name, value];
}
}
}
}
}
[propertyInfo appendString:@"===================================================================================================="];
free(properties);
return propertyInfo;
}