在开发过程中会经常通过description方法输出model的所有属性和属性值来查看model是否正确赋值。LBYDescription 库可以简单的通过一行代码获取到对象的所有属性以及属性值。
LBYDescription 使用姿势:
导入方式:
- 方式一:直接将NSObject+LBYDescription.h和NSObject+LBYDescription.m拖到项目中。
- 方式二:通过pod库导入。
pod 'LBYDescription', '~> 1.0.0'
使用流程:
第一步:import头文件
#import "NSObject+LBYDescription.h"
第二步:在description方法中执行代码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;
}
网友评论