码迷,mamicode.com
首页 > 移动开发 > 详细

iOS 利用runtime调用方法

时间:2015-07-12 18:44:14      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:

利用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];

}

iOS 利用runtime调用方法

标签:

原文地址:http://www.cnblogs.com/oumygade/p/4641231.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!