iOS NSClassFromString
2017-05-26 本文已影响1826人
aaa000
1.通过字符串创建类和对象
Class A = NSClassFromString(@"AAA");
id cls = [[NSClassFromString(@"ViewController") alloc]init];
2.通过类获取类名称字符串
NSString *str = NSStringFromClass(self);
3.通过字符串(已存在的方法名称)获取一个SEL
SEL selector = NSSelectorFromString(@"textFunc");
4.执行某个类的 每一个方法
//没有参数 类方法 返回值为BOOL
Class AAA = NSClassFromString(@"WXSocialAgent");
SEL selector = NSSelectorFromString(@"isWXAppInstalled");
IMP imp = [AAA methodForSelector:selector];
BOOL (*func)(Class, SEL) = (BOOL (*)(Class,SEL))imp;
BOOL flag = func(AAA,selector);
//有一个参数 类方法 无返回值
Class AAA = NSClassFromString(@"WXSocialAgent");
SEL selector = NSSelectorFromString(@"isWXAppInstalled");
IMP imp = [AAA methodForSelector:selector];
void (*func)(Class, SEL,id) = (void (*)(Class,SEL,id))imp;
func(AAA,selector,@"abc");
//有多个参数 类方法 无返回值
Class AAA = NSClassFromString(@"WXSocialAgent");
SEL selector = NSSelectorFromString(@"isWXAppInstalled");
IMP imp = [AAA methodForSelector:selector];
void (*func)(Class, SEL,id,id) = (void (*)(Class,SEL,id,id))imp;
func(AAA,selector,@"abc",@"ddf");
//有一个参数 实例方法 无返回值
id aaa = [[NSClassFromString(@"WXSocialAgent") alloc]init];
SEL selector = NSSelectorFromString(@"isWXAppInstalled");
IMP imp = [aaa methodForSelector:selector];
void (*func)(id, SEL,id) = (void (*)(id,SEL,id))imp;
func(aaa,selector,@"abc");
// 调用函数 有返回值
id c = [[NSClassFromString(@"TestClass") alloc]init];
SEL s = NSSelectorFromString(@"textFunction:");
IMP imp = [c methodForSelector:s];
void (*func)(Class, SEL,void(^)(NSString *)) = (void (*)(Class,SEL,void(^)(NSString *)))imp;
if (c && [c respondsToSelector:s]) {
func(c,s,^(NSString *string){
NSLog(@"%@",string);
});
}