关于ios:runtime-获取对象属性字典

38次阅读

共计 1528 个字符,预计需要花费 4 分钟才能阅读完成。


#import "NSObject+object_runtime.h"
#import <objc/runtime.h>

@implementation NSObject (object_runtime)

/**
    获取对象的属性和属性值字典
 */
- (NSDictionary*)objectGetPropertyKeysValues
{NSMutableDictionary* dic = [NSMutableDictionary dictionary];
    unsigned int count;
    objc_property_t * prop_list = class_copyPropertyList([self class], &count);
    for (int i=0; i<count; i++) {objc_property_t prop = prop_list[i];
        const char * prop_name = property_getName(prop);
        NSString* propName = [NSString stringWithUTF8String:prop_name];
        id propVal = [self valueForKey:propName];
        if (propVal) {[dic setObject:propVal forKey:propName];
        } else {[dic setObject:[NSNull null] forKey:propName];
        }
    }
    free(prop_list);
    return dic;
}
 
/**
    获取类的属性列表
 */
+ (NSArray*)classGetPropertyList
{
    unsigned int count;
    objc_property_t * prop_list = class_copyPropertyList([self class], &count);
    NSMutableArray * propsArr = [NSMutableArray arrayWithCapacity:count];
    for (int i=0; i<count; i++) {objc_property_t prop = prop_list[i];
        const char * prop_name = property_getName(prop);
        NSString* propName = [NSString stringWithUTF8String:prop_name];
        [propsArr addObject:propName];
    }
    free(prop_list);
    return propsArr;
}

/**
    获取类的办法列表
 */
+ (NSArray*)classGetMethodList
{
    unsigned int count;
    Method * method_list = class_copyMethodList([self class], &count);
    NSMutableArray * array = [NSMutableArray arrayWithCapacity:count];
    for (int i = 0; i<count; i++) {Method m = method_list[i];
        const char * name = sel_getName(method_getName(m));
        //IMP imp = method_getImplementation(m);
        //int args = method_getNumberOfArguments(m);
        //const char * encoding = method_getTypeEncoding(m);
        [array addObject:[NSString stringWithUTF8String:name]];
    }
    free(method_list);
    return array;
}

@end

正文完
 0