继续搬砖之Runtime之objc_msgSend

明确几个概念:
  • 方法调用的本质,就是让对象发送消息。
  • NSNumber *isEnough = [person eatEnough:@(20)];该方法的调用时会转化为objc_msgSend进行调用,eatEnough:以及后面的参数形成了一个的消息。
  • 看一下objc_msgSend这个方法的系统定义,void objc_msgSend(void /* id self, SEL op, ... */ ),消息发送最少包括两个参数,一个id类型,一个SEL类型。
  • 当对象对应方法列表中查询不到这个方法时,并且不做任何处理的情况下,系统会抛出异常。(⚠️:可以转发这个消息,来消除异常)
(对于基础类型不了解的同志们可以查看 这里

消息发送到最后对应到方法实现的查找过程:SEL -> Method -> IMP,最后利用IMP函数指针调用方法,流程图如下:

image

之前说过关于元类的知识,上图也同样反映出,类方法和实例方法处理起来有些许的差别。

image

下面我们来说一下具体的用法

  • 应用场景:随意调用所有的方法,并且为实现不会崩溃。(是不是超牛逼)
    在我们开发中,有些方法我们不愿在.h中公开,导入某些头文件一不注意就会循环引用。并且很多时候会造成代码的耦合性上升,任何功能的SDK特性才是一个程序员代码实力的象征。

⚠️ 使用objc_msgSend这个方法的前提是你需要在BuildSettings中设置Enable Strict Checking of objc_msgSend CallsYES,否则会报错。
⚠️ 不要以为导入头文件#import 就万事大吉了,同时记得导入#import

首先,创建一个Person类,.h中不公开任何方法 ,在.m中实现如下方法:

/**
 *吃饭实例方法  无参数 无返回值
 */
-(void)eat{
    NSLog(@"eat_person");
}
/**
 *吃饭类方法  无参数  无返回值
 */
+(void)eat{
    NSLog(@"eat_class");
}

/**
 *睡觉实例方法  有参数 无返回值
 */
-(void)sleepOfHour:(NSNumber*)hour{
    NSLog(@"sleep_person_%@",hour);
}
/**
 *睡觉类方法  有参数 无返回值
 */
+(void)sleepOfHour:(NSNumber*)hour{
    NSLog(@"sleep_class_%@",hour);
}

/**
 *是否吃饱实例方法 有参数 有返回值
 */
-(NSNumber*)eatEnough:(NSNumber*)breadCount{
    NSLog(@"breadCount_person_%@",breadCount);
    return @(1);
}

/**
 *是否吃饱类方法 有参数 有返回值
 */
+(NSNumber*)eatEnough:(NSNumber*)breadCount{
    NSLog(@"breadCount_class_%@",breadCount);
    return @(0);
}

runtime方法封装:

.h
#pragma mark - objc_msgSend (限制五个个参数及以内)
/**
 *实例方法
 */
+(id)msgSendToObj:(id)obj Selector:(SEL)selector Prarms:(NSArray*)params NeedReturn:(BOOL)needReturn;
/**
 *类方法
 */
+(id)msgSendToClass:(Class)YSClass Selector:(SEL)selector Prarms:(NSArray*)params NeedReturn:(BOOL)needReturn;
-----------------------------------------------------------
.m
#pragma mark - objc_msgSend

+(id)msgSendToObj:(id)obj Selector:(SEL)selector Prarms:(NSArray*)params NeedReturn:(BOOL)needReturn{
    id returnValue = nil;
    NSInteger paramsCount = params.count;
    NSMutableArray *params_M = [NSMutableArray arrayWithArray:params];
    //
    while (params_M.count < 5) {
        [params_M addObject:@""];
    }
    params = params_M;
    //
    if (obj && selector && [obj respondsToSelector:selector] && paramsCount <= 5) {
        if (needReturn) {
            returnValue = ((id (*) (id, SEL, id, id , id, id, id)) (void *)objc_msgSend) (obj, selector, params[0], params[1], params[2], params[3], params[4]);
        }else{
            ((void (*) (id, SEL, id, id , id, id, id)) (void *)objc_msgSend)(obj, selector,  params[0], params[1], params[2], params[3], params[4]);
        }
    }
    return returnValue;
}

+(id)msgSendToClass:(Class)YSClass Selector:(SEL)selector Prarms:(NSArray*)params NeedReturn:(BOOL)needReturn{
    id returnValue = nil;
    NSInteger paramsCount = params.count;
    NSMutableArray *params_M = [NSMutableArray arrayWithArray:params];
    //
    while (params_M.count < 5) {
        [params_M addObject:@""];
    }
    params = params_M;
    //
    Method method = class_getClassMethod(YSClass, selector);
    //
    if (YSClass && selector && (int)method != 0 && paramsCount <= 5) {
        if (needReturn) {
            returnValue = ((id (*) (id, SEL, id, id , id, id, id)) (void *)objc_msgSend) (YSClass, selector, params[0], params[1], params[2], params[3], params[4]);
        }else{
            ((void (*) (id, SEL, id, id , id, id, id)) (void *)objc_msgSend)(YSClass, selector,  params[0], params[1], params[2], params[3], params[4]);
        }
    }
    return returnValue;
}

在工程中调用方法如下:

Person* person = [[Person alloc] init];
[NSObject msgSendToObj:person Selector:NSSelectorFromString(@"eat") Prarms:nil NeedReturn:NO];
[NSObject msgSendToClass:NSClassFromString(@"Person") Selector:NSSelectorFromString(@"eat") Prarms:nil NeedReturn:NO];
//
[NSObject msgSendToObj:person Selector:NSSelectorFromString(@"sleepOfHour:") Prarms:@[@(10)] NeedReturn:NO];
[NSObject msgSendToClass:NSClassFromString(@"Person") Selector:NSSelectorFromString(@"sleepOfHour:") Prarms:@[@(8)] NeedReturn:NO];
//
id objR = [NSObject msgSendToObj:person Selector:NSSelectorFromString(@"eatEnough:") Prarms:@[@(100)] NeedReturn:YES];
id classR = [NSObject msgSendToClass:NSClassFromString(@"Person") Selector:NSSelectorFromString(@"eatEnough:") Prarms:@[@(100)] NeedReturn:YES];
NSLog(@"objR_%@ classR_%@", objR, classR);

打印结果:

RuntimeSkill[2126:215490] eat_person
RuntimeSkill[2126:215490] eat_class
RuntimeSkill[2126:215490] sleep_person_10
RuntimeSkill[2126:215490] sleep_class_8
RuntimeSkill[2126:215490] breadCount_person_100
RuntimeSkill[2126:215490] breadCount_class_100
RuntimeSkill[2126:215490] objR_1 classR_0

通过上面的讲解和代码,我姑且认为你了解了消息发送的原理以及实用技巧,但是有限个参数的限制真的是头疼,后来发现了一个东西NSInvocation。于是扩展出了下面一套不限参数的方法调用机制:

.h
#pragma mark - NSInvocation (不限参数)
/**
 *实例方法
 */
+(id)msgSendToObj_invocation:(id)obj Selector:(SEL)selector Prarms:(NSArray*)params NeedReturn:(BOOL)needReturn;
/**
 *类方法
 */
+(id)msgSendToClass_invocation:(Class)YSClass Selector:(SEL)selector Prarms:(NSArray*)params NeedReturn:(BOOL)needReturn;
------------------------------------------------------------------
.m
#pragma mark - NSInvocation (不限参数)
+(id)msgSendToObj_invocation:(id)obj Selector:(SEL)selector Prarms:(NSArray*)params NeedReturn:(BOOL)needReturn{
    id value = nil;
    if (obj && selector) {
        if ([obj respondsToSelector:selector]) {
            NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[[obj class] instanceMethodSignatureForSelector:selector]];
            [invocation setSelector:selector];
            [invocation setTarget:obj];
            for (int i=0; i < params.count; i++) {
                id ref = params[i];
                [invocation setArgument:&ref atIndex:2+i];
            }
            [invocation invoke];//perform 的传参表达方式
            if(needReturn){//获得返回值
                void *vvl = nil;
                [invocation getReturnValue:&vvl];
                value = (__bridge id)vvl;
            }
        }else{
#ifdef _YSDebugLog
            NSLog(@"msgToTarget unRespondsToSelector -->>> %@ %@",obj,menthed);
#endif
        }
    }
    return value;
}
+(id)msgSendToClass_invocation:(Class)YSClass Selector:(SEL)selector Prarms:(NSArray*)params NeedReturn:(BOOL)needReturn{
    id value = nil;
    Method method = class_getClassMethod(YSClass, selector);
    if((int)method != 0){
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[YSClass methodSignatureForSelector:selector]];
        [invocation setSelector:selector];
        [invocation setTarget:YSClass];
        for (int i=0; i < params.count; i++) {
            id ref = params[i];
            [invocation setArgument:&ref atIndex:2+i];
        }
        [invocation invoke];//perform 的传参表达方式
        if(needReturn){//获得返回值
            void *vvl = nil;
            [invocation getReturnValue:&vvl];
            value = (__bridge id)vvl;
        }
    }else{
#ifdef _YSDebugLog
        NSLog(@"msgToClass unRespondsToSelector -->>> %@ %@",YSClass,menthed);
#endif
    }
    return value;
}

调用方法:

[NSObject msgSendToObj_invocation:person Selector:NSSelectorFromString(@"eat") Prarms:nil NeedReturn:NO];
[NSObject msgSendToClass_invocation:NSClassFromString(@"Person") Selector:NSSelectorFromString(@"eat") Prarms:nil NeedReturn:NO];
//
[NSObject msgSendToObj_invocation:person Selector:NSSelectorFromString(@"sleepOfHour:") Prarms:@[@(10)] NeedReturn:NO];
[NSObject msgSendToClass_invocation:NSClassFromString(@"Person") Selector:NSSelectorFromString(@"sleepOfHour:") Prarms:@[@(8)] NeedReturn:NO];
//
id objR_in = [NSObject msgSendToObj_invocation:person Selector:NSSelectorFromString(@"eatEnough:") Prarms:@[@(100)] NeedReturn:YES];
id classR_in = [NSObject msgSendToClass_invocation:NSClassFromString(@"Person") Selector:NSSelectorFromString(@"eatEnough:") Prarms:@[@(100)] NeedReturn:YES];
NSLog(@"objR_in_%@ classR_in_%@", objR_in, classR_in);

打印结果:

RuntimeSkill[2150:221988] eat_person
RuntimeSkill[2150:221988] eat_class
RuntimeSkill[2150:221988] sleep_person_10
RuntimeSkill[2150:221988] sleep_class_8
RuntimeSkill[2150:221988] breadCount_person_100
RuntimeSkill[2150:221988] breadCount_class_100
RuntimeSkill[2150:221988] objR_in_1 classR_in_0

有了这个原则,你就可以肆无忌惮的调用管他公布公不公开的方法,换一个角度,也就是可以通过get方法获取.m中未公开属性值。方法是这个方法,但每个人可能都有不同的见解,抛砖引玉,你可能看了之后能找到更牛逼的实用领域,到时候记得来嘲讽我!!!

image

作者:MrHippo
链接:https://www.jianshu.com/p/38bbde2c5632
来源:
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

你可能感兴趣的:(继续搬砖之Runtime之objc_msgSend)