iOS 动态调用方法

2018-10-19  本文已影响0人  Sh1mmer

我们可以通过传递过来的方法名称来执行方法

          SEL selector = NSSelectorFromString(@"tempAction:");
          NSDictionary *paramter = @{@"a":@"1"};
          IMP imp = [self methodForSelector:selector];
          void(*func)(id, SEL, NSDictionary*) = (void *)imp;
          func(self, selector,paramter);
//================================
- (void)tempAction:(NSDictionary *)dic{
    NSLog(@"%@",dic);
}

当然我们也可以通过这个方法去执行其他类里的方法
//在classB中执行下面代码;
        Class class = NSClassFromString(@"classA");
        SEL selector = NSSelectorFromString(@"classAAction:");
        NSObject *instance =  [class new];
        NSDictionary *paramter = @{@"a":@"1"};
        IMP imp = [instance methodForSelector:selector];
        void(*func)(id, SEL, NSDictionary*) = (void *)imp;
        func(self, selector,paramter);
//==================
//classA中在.m里;(不需要在.h中声明classAAction方法)
- (void)classAAction:(NSDictionary *)temp{
    NSLog(@"%@",temp)
}

这里执行方法的返回值和参数大家可以灵活更换
上一篇下一篇

猜你喜欢

热点阅读