Runtime

作者: bytebytebyte | 来源:发表于2019-08-10 22:29 被阅读0次

创建一个类

  • (void)pushToAnyVCWithData:(NSDictionary *)dataDict{
    //
    const char *clsName = [dataDict[@"class"] UTF8String];
    Class cls = objc_getClass(clsName);
    // 1: 创建类
    if (!cls) {
    Class superClass = [UIViewController class];
    cls = objc_allocateClassPair(superClass, clsName, 0);
    class_addIvar(cls, "ending", sizeof(NSString *), log2(sizeof(NSString *)), @encode(NSString *));
    class_addIvar(cls, "show_lb", sizeof(UILabel *), log2(sizeof(UILabel *)), @encode(UILabel *));
    objc_registerClassPair(cls);

      Method method = class_getInstanceMethod([self class], @selector(lg_instancemethod));
      IMP methodIMP = method_getImplementation(method);
      const char *types = method_getTypeEncoding(method);
      BOOL rest = class_addMethod(cls, @selector(viewDidLoad), methodIMP, types);
      NSLog(@"rest == %d",rest);
    

    }

    // 实例化对象
    id instance = nil;
    @try {
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    instance = [sb instantiateViewControllerWithIdentifier:dataDict[@"class"]];
    } @catch (NSException *exception) {

      instance = [[cls alloc] init];
    

    } @finally {
    NSLog(@"OK");
    }

    NSDictionary *dict = dataDict[@"data"];
    [dict enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
    // 检测是否存在key的属性
    if (class_getProperty(cls, [key UTF8String])) {
    [instance setValue:obj forKey:key];
    }
    // 检测是否存在key的变量
    else if (class_getInstanceVariable(cls, [key UTF8String])){
    [instance setValue:obj forKey:key];
    }
    }];

[self.navigationController pushViewController:instance animated:YES];

}

// self ?
// objc_msgSend(id self,)
// self 型参
// self class [super class]

  • (void)lg_instancemethod {
    [super viewDidLoad];

    [self setValue:[UIColor orangeColor] forKeyPath:@"view.backgroundColor"];
    [self setValue:[[UILabel alloc] initWithFrame:CGRectMake(100, 200, 200, 30)] forKey:@"show_lb"];
    UILabel *show_lb = [self valueForKey:@"show_lb"];
    [[self valueForKey:@"view"] addSubview:show_lb];
    show_lb.text = [self valueForKey:@"ending"];
    show_lb.font = [UIFont systemFontOfSize:14];
    show_lb.textColor = [UIColor blackColor];
    show_lb.textAlignment = NSTextAlignmentCenter;
    show_lb.backgroundColor = [UIColor whiteColor];
    NSLog(@"hello word");
    }

相关文章

网友评论

      本文标题:Runtime

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