runtime消息发送

    xiaoxiao2021-03-25  105

    一、runtime简介

    RunTime简称运行时。OC就是运行时机制,也就是在运行时候的一些机制,其中最主要的是消息机制。对于C语言,函数的调用在编译的时候会决定调用哪个函数对于OC的函数,属于动态调用过程,在编译的时候并不能决定真正调用哪个函数,只有在真正运行的时候才会根据函数的名称找到对应的函数来调用。

    1.发送消息

    OC方法的调用就是让对象发消息,objc_msgSend()方法就是 用来发送消息的, Permissions *p = [[Permissions alloc] init]; [p waitUrgeOrder];其实最后会转成 objc_msgSend(p,@selector(waitUrgeOrder)); 如果有参数后面也可填入参数   SEL sel = @selector(alertWithString:); objc_msgSend([Tools class], sel, @"参数");

    最近在ios8时,发现如下报错:

    Too many arguments to function call, expected 0, have 3

    解决方法

    ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)[Tools class], sel, @"参数"); objc_msgSend(receiver, selector, arg1, arg2, ...) 参数:receiver   接受对象            selector    方法选择器           arge1     参数 例如: 创建类 Tools .h中有个弹窗方法 需要传人参数str #import <Foundation/Foundation.h> @interface Tools : NSObject +(void)alertWithString:(NSString *)str; @end.m  #import "Tools.h" @implementation Tools +(void)alertWithString:(NSString *)str { UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"提示" message:str delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil]; [alert show]; } @end 其他类中调用 - (instancetype)init { self = [super init]; if (self) { [Tools alertWithString:@"111"]; SEL sel = @selector(alertWithString:); ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)[Tools class], sel, @"你好runtime"); } return self; }最终效果为 技术有限 如有什么不对的地方 希望大牛 能多多指导!!!!

    转载请注明原文地址: https://ju.6miu.com/read-18720.html

    最新回复(0)