您的位置:首页 > 移动开发 > Objective-C

第01天实战技术(08):Runtime(消息机制调用多个参数)

2017-03-24 00:00 435 查看
#####一、什么时候需要用runtime,消息机制

1.装逼 , YYKit
2.不得不用runtime消息机制,可以帮助我们调用私有的方法.

#####二、什么时候runtime,方便调用流程

1.调用没有实现的方法,会报错

Person *p = objc_msgSend(objc_getClass("Person"), sel_registerName("alloc"));
p = objc_msgSend(p, sel_registerName("inito"));
---错误信息 没有inito这个方法
'NSInvalidArgumentException', reason: '-[Person inito]: unrecognized selector sent to instance 0x60000001caa0'
*** First throw call stack


2.调用私有方法
objc_msgSend(对象, @selector(方法名))


Person *p = objc_msgSend(objc_getClass("Person"), sel_registerName("alloc"));
p = objc_msgSend(p, sel_registerName("init"));
objc_msgSend(p, @selector(eat)); // 可以调用私有的方法


3.调用带参数的方法
objc_msgSend(对象, @selector(方法名:),参数列表...)


Person *p = objc_msgSend(objc_getClass("Person"), sel_registerName("alloc"));
p = objc_msgSend(p, sel_registerName("init"));
objc_msgSend(p, @selector(run:),15);


code

Person类

#import <Foundation/Foundation.h>

@interface Person : NSObject
//- (void)eat;
- (void)run:(NSInteger )metre;

@end

----
#import "Person.h"

@implementation Person
- (void)eat
{
NSLog(@"-- eat");
}

- (void)run:(NSInteger )metre
{
NSLog(@"-- 跑了%ld公里",metre);
}
@end


#import "ViewController.h"
#import <objc/message.h>
#import "Person.h"
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];

// TODO: 讲解下 什么时候runtime,方便调用流程
//Person *p = [Person alloc];

// objc_msgSend([Person class], @selector(alloc)); ==== objc_msgSend(objc_getClass("Person"), sel_registerName("alloc"));
// objc_msgSend(p, @selector(alloc)); === objc_msgSend(p, sel_registerName("init"));
Person *p = objc_msgSend(objc_getClass("Person"), sel_registerName("alloc"));
p = objc_msgSend(p, sel_registerName("init"));
/**
p = objc_msgSend(p, sel_registerName("inito"));
'NSInvalidArgumentException', reason: '-[Person inito]: unrecognized selector sent to instance 0x60000001caa0'
*** First throw call stack
*/

// 调用eat方法
// [p eat];
objc_msgSend(p, @selector(eat)); // 可以调用私有的方法
// <#SEL op, ...#>  SEL 方法 ,...方法的第一个参数
objc_msgSend(p, @selector(run:),15);

}
@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Objective-C RunTime