标签:
利用runtime调用方法,可实现不做import,直接调用
// Build Setting--> Apple LLVM 6.0 - Preprocessing--> Enable Strict Checking of objc_msgSend Calls 改为 NO
- (void)execFunction2
{
NSString *functionName = @"runWithFriend:";
NSString *className = @"People";
NSString *friend = @"妹子";
SEL runAction = NSSelectorFromString(functionName);
Class peopleClass = NSClassFromString(className);
objc_msgSend(peopleClass, runAction, friend);
}
static NSMutableDictionary *cache;
- (void)execFunction
{
if (!cache)
cache = [NSMutableDictionary dictionary];
NSString *functionName = @"runWithFriend:";
NSString *className = @"People";
NSString *friend = @"妹子";
SEL runAction = NSSelectorFromString(functionName);
Class peopleClass = NSClassFromString(className);
NSMethodSignature *runSig;
if ([cache objectForKey:functionName]) {
runSig = [cache objectForKey:functionName];
} else {
// methodSignatureForSelector:比较耗费性能, 所以最好把签名缓存起来
runSig = [peopleClass methodSignatureForSelector:runAction];
[cache setObject:runSig forKey:functionName];
}
NSInvocation *inv = [NSInvocation invocationWithMethodSignature:runSig];
[inv setSelector:runAction];
[inv setArgument:&friend atIndex:2];
[inv invokeWithTarget:peopleClass];
}
标签:
原文地址:http://www.cnblogs.com/oumygade/p/4641231.html