runtime基本用法

2016-09-21  本文已影响0人  赖熊

1 当我们动态加载某个类的时候,可以用到runtime,可以便捷的获取到动态加载类的所有信息 (属性,属性名)

 /**
     *测试自动生成某个类
     */
    NSDictionary *dict =@{
                            @"class": @"WaitViewController",
                            @"property": @{
                            @"ID": @"123",
                            @"type": @"12"
                            }
    };
    NSString *class =[NSString stringWithFormat:@"%@",dict[@"class"]];
    const char *className =[class cStringUsingEncoding:NSUTF8StringEncoding];
    Class newClass =objc_getClass(className);
    if (!newClass) {
        Class superClass =[UIViewController class];
        newClass =objc_allocateClassPair(superClass, className, 0);
        objc_registerClassPair(newClass);
        
    }
    id instance =[[newClass alloc] init];
    NSDictionary *propertys =dict[@"property"];
    [propertys enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
//加载类中的属性
        NSLog(@"%@",key);
        unsigned int outCount, i;
        objc_property_t *property1 =class_copyPropertyList([instance class], &outCount);
        for (i=0; i<outCount; i++) {
            objc_property_t property =property1[i];
            NSLog(@"%s",property_getAttributes(property));
//            NSLog(@"%@",method_getName((__bridge Method)(instance)));
            NSString *propertyName =[[NSString alloc] initWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
            if ([propertyName isEqualToString:key]) {
                NSLog(@"yes");
            }
        }
        
        
    }];

上一篇下一篇

猜你喜欢

热点阅读