首页 > 代码库 > ios反射

ios反射

<pre name="code" class="objc"><pre name="code" class="objc">    Class cls = NSClassFromString(@"ClassName");
    
    id a= [[cls  alloc]  init];
    
//    调用方法
    NSString *selectorName = @"selector:";//方法名
    NSString *selectorParame = @"aaa";    //方法参数
    SEL selector = NSSelectorFromString(selectorName);
    if ([a respondsToSelector:selector]) {
        objc_msgSend(a,selector,selectorParame);//执行方法

    }
    
//     参数设置
    NSString *parameter = @"parameter";  //参数名
    NSString *first = [[parameter substringToIndex:1] uppercaseString];
    NSString *next  = [parameter substringWithRange:NSMakeRange(1,parameter.length)];
    NSString *parameterName = [NSString stringWithFormat:@"set%@%@:", first,next];
    
    SEL parameterSelector = NSSelectorFromString(parameterName);
    if ([a respondsToSelector:parameterSelector]) {
        objc_msgSend(a,parameterSelector,@"parameterValue");
    }


ios反射