1:开发中什么时候使用Runtime?
>01-有些框架如YYKit等等很多都是使用运行时去写的,虽然规范,但是装逼
>02-有些不得不用Runtime消息机制,它可以帮助我们调用私有的方法:就是外面没有暴露出来的一些方法或者系统里面的一些私有api
2:怎样使用消息机制调用不带参数方法和带有多个参数的方法?
代码演示:
- (void)viewDidLoad {
[super viewDidLoad];
//Person *p = [Person alloc];
Person *p = objc_msgSend(objc_getClass("Person"), @selector(alloc));
//p = [p init];
p = objc_msgSend(p, sel_registerName("init"));
// 调用eat方法
objc_msgSend(p, @selector(eat));
// 如果eat方法没有暴露出来,使用[p eat]就会报错,但是使用Runtime就可以调用
// 调用有参数的方法:
objc_msgSend(p, @selector(run:),200);
}
创建一个Person类:
#import <Foundation/Foundation.h>
@interface Person : NSObject
- (void)eat;
- (void)run:(NSInteger)metre;
@end
实现Person类中的几个方法:
#import "Person.h"
@implementation Person
- (void)eat {
NSLog(@"吃");
}
- (void)run:(NSInteger)metre {
NSLog(@"今天我跑了%ld米",metre);
}
@end
意见反馈邮件:1415429879@qq.com
欢迎你们的阅读和赞赏、谢谢!