美文网首页
iOS:debug模式下调试model

iOS:debug模式下调试model

作者: 豆浆油条cc | 来源:发表于2019-12-04 16:50 被阅读0次

日常开发中,使用控制台打印model的时候,只能打印出model地址,为了能够输出model所有属性值,及类型,可以利用debugDescription方法,因为debugDescription是在断点+控制台输出的时候走的。
配合runtime中的class_copyPropertyList方法获取所有属性。

1.0 :获取类中的所有属性类及值

+ (NSDictionary*)getPropertyDicFromClass:(id)NSObject{
    u_int count = 0;
    NSMutableDictionary *resultDict = [NSMutableDictionary dictionaryWithCapacity:count];
    objc_property_t * properties  = class_copyPropertyList([NSObject class], &count);
    for (int i=0; i<count; i++) {
        const char *name = property_getName(properties[i]);
        NSString *propertyName = [NSString stringWithUTF8String:name];
        if (propertyName && [NSObject valueForKey:propertyName]) {
            id propertyValue = [NSObject valueForKey:propertyName];
            if ([propertyValue isKindOfClass:[UIViewController class]]) {
                [resultDict setObject:propertyName forKey:propertyName];
            }else{
                [resultDict setObject:propertyValue forKey:propertyName];
            }
        }
    }
    
    free(properties);//防止内存泄漏
    return resultDict;
}
+ (NSString*)descriptionMehtod:(NSObject*)NSObject{
    
    NSDictionary* dic = [MethodSwizzingTool getPropertyDicFromClass:NSObject];
    NSMutableString* str = [NSMutableString string];
    [dic enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        [str appendString:[NSString stringWithFormat:@"%@--->%@\r\n",key,obj]];
    }];
    return str;
}

2.0 : 创建一个baseModel类,所有model可以基础它,重写debugDescription调用封装好的方法

-(NSString *)debugDescription{
    NSLog(@"1");
    return [NSString stringWithFormat:@"className:%@\r\n%@\r\n%@",[self class],self,[[self class] descriptionMehtod:self]];
}

相关文章

网友评论

      本文标题:iOS:debug模式下调试model

      本文链接:https://www.haomeiwen.com/subject/zlulgctx.html