动态创建类 并且调用类方法

2017-01-14  本文已影响156人  SpursGo

解耦合是一个老生常谈的话题,oc是一门动态语言,所以如何再.m文件中不导入其他.h文件 就可以调用一个类的方法,是非常诱人的一件事

1.通过performseletor来动态调用方法

    Class clzz = NSClassFromString(@"Person");
    id instance = [[clzz alloc]init];
    SEL seletor = NSSelectorFromString(@"run:");
    [instance performSelector:seletor withObject:nil];

但是这样xcode会有一个警告,具体原因大家可以去谷歌搜一把,
2.优化版本

    Class clzz = NSClassFromString(@"Person");
    id instance = [[clzz alloc]init];
    SEL seletor = NSSelectorFromString(@"run:");
    NSDictionary * dic = @{@"key":@"ss",@"key1":@"ss"};
    IMP imp = [instance methodForSelector:seletor];
    void (*func)(id, SEL,NSDictionary *) = (void *)imp;
    func(instance, seletor,dic);

3.一种比较浪费时间 的方法 NSInvocation

    Class clzz = NSClassFromString(@"Person");
    id instance = [[clzz alloc]init];
    NSMethodSignature *signture = [instance methodSignatureForSelector:@selector(run:)];
    NSLog(@"num of arguments is %zd",signture.numberOfArguments);
    NSLog(@"arguments0 is %s",[signture getArgumentTypeAtIndex:0]);
    NSLog(@"arguments1 is %s",[signture getArgumentTypeAtIndex:1]);
    NSLog(@"arguments2 is %s",[signture getArgumentTypeAtIndex:2]);
    NSInvocation * invocation = [NSInvocati on invocationWithMethodSignature:signture];
    NSDictionary * dic = @{@"key":@"ss",@"key1":@"ss"};
    [invocation setArgument:&dic atIndex:2];
    [invocation setTarget:instance];
    [invocation setSelector:@selector(run:)];
    [invocation invoke];
上一篇下一篇

猜你喜欢

热点阅读