美文网首页
OC:打印自定义的类的属性信息

OC:打印自定义的类的属性信息

作者: 春暖花已开 | 来源:发表于2018-11-20 10:38 被阅读12次
    #import <Foundation/Foundation.h>
    
    @interface MZBaseModel : NSObject
    
    @end
    
    #import "MZBaseModel.h"
    
    #import <objc/runtime.h>
    
    @implementation MZBaseModel
    
    #ifdef DEBUG
    - (NSString *)description {
        
        id modelClass = [self class];
        unsigned int count, i;
        objc_property_t *properties = class_copyPropertyList(modelClass, &count);
        
        NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:count];
        
        //遍历出所有的属性key/value
        for (i = 0; i < count; i++) {
            objc_property_t property = properties[i];
            NSString *propertyName = [NSString stringWithUTF8String:property_getName(property)];
            id value = [[self valueForKey:propertyName] description];
            [dict setObject:value forKey:propertyName];
        }
        return [NSString stringWithFormat:@"<%@: %p> %@", [self class], self, dict];
    }
    #endif
    
    @end
    
    

    相关文章

      网友评论

          本文标题:OC:打印自定义的类的属性信息

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