iOS 动态调用方法
示例:
- (void)bugly
{
dispatch_async(dispatch_get_global_queue(0, 0), ^{
if (NSClassFromString(@"Bugly")) {
Class clazz = NSClassFromString(@"Bugly");
SEL sel = NSSelectorFromString(@"startWithAppId:config:");
IMP imp = [clazz methodForSelector:sel];
void (*IMP_startWithAppId)(id, SEL, NSString *, id) = (void *)imp;
NSDictionary *info = [[NSBundle mainBundle] infoDictionary];
Class buglyConfig = NSClassFromString(@"BuglyConfig");
id config = [[buglyConfig alloc]init];
[config setValue:@"NO" forKey:@"debugMode"];
[config setValue:[info objectForKey:(NSString *)kCFBundleIdentifierKey] forKey:@"channel"];
[config setValue:[info objectForKey:(NSString *)kCFBundleNameKey] forKey:@"version"];
IMP_startWithAppId(clazz, sel, BUGLY_KEY, config);
}
});
}
如上述示例代码,是对接Bugly的一段代码。我们APP里面并不需要导入bugly的类,通过拿到类的IMP ,来直接调用bugly的初始化方法,达到低耦合的目的。
在处理一些第三方框架或是服务的时候,建议这样处理比较灵活。
Class clazz = NSClassFromString(@"XXXLoginViewController");
SEL sel = NSSelectorFromString(@"sharedInstance");
IMP imp = [clazz methodForSelector:sel];
id (*setUserDataFunc)(id, SEL) = (void *)imp;
id loginVC = setUserDataFunc(clazz,sel);
UIButton * btn = [loginVC valueForKey:@"mobileValBtn"];
解决问题的能力很关键~(iOS开发交流群:219926126)