Runtime消息传送

person.h
#import<Foundation/Foundation.h>

@interfacePerson :NSObject

+ (void)eat;

- (void)run:(int)age;

- (void)eat;

@end

person.m
#import"Person.h"

@implementationPerson
- (void)eat
{
   NSLog(@"对象方法-吃东西");
}

+ (void)eat
{
   NSLog(@"类方法-吃东西");
}

- (void)run:(int)age
{
   NSLog(@"%d",age);
}
@end

实现runtime实现的位置
#import"ViewController.h" #import"Person.h" //使用运行时的第一步:导入<objc/message.h> //第二步:Build Setting ->搜索msg ->设置属性为No #import<objc/message.h> @interfaceViewController() @end @implementationViewController - (void)viewDidLoad { [superviewDidLoad]; // Do any additional setup after loading the view, typically from a nib. Person*p = [[Personalloc]init]; //吃东西 [peat]; // OC:运行时机制,消息机制是运行时机制最重要的机制 //消息机制:任何方法调用,本质都是发送消息 // SEL:方法编号,根据方法编号就可以找到对应方法实现 [pperformSelector:@selector(eat)]; //运行时,发送消息,谁做事情就那谁 // xcode5之后,苹果不建议使用底层方法 // xcode5之后,使用运行时. //让p发送消息 objc_msgSend(p,@selector(eat)); //传参 objc_msgSend(p,@selector(run:),10); //类名调用类方法,本质类名转换成类对象 [Person eat]; //获取类对象 Class personClass = [Personclass]; [personClass performSelector:@selector(eat)]; //运行时 objc_msgSend(personClass,@selector(eat)); }

源自小马哥教学视频

原文地址:https://www.cnblogs.com/mapanguan/p/5498147.html