Runtime(二)

2017-01-18  本文已影响32人  952625a28d0d
#import "ViewController.h"
#import "Person.h"
#import <objc/message.h>    // 默认导入Runtime

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    Person *p = [[Person alloc] init];
//    [p run];
    
    // 在Xcode5.0之后 苹果不建议使用底层函数
    // 发送一个消息给 p
    objc_msgSend(p,@selector(run));
    objc_msgSend(p, @selector(earWithFoot:),@"香蕉");
    
    // 调用类方法 Class类型也是一个特殊的对象
    Class personClass = [Person class];
    // 不管是对象还是类 都可以发送消息
    objc_msgSend(personClass, @selector(run));
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
#import <Foundation/Foundation.h>

@interface Person : NSObject

+ (void)run;

- (void)run;

- (void)earWithFoot:(NSString *)foot;

@end
#import "Person.h"

@implementation Person

- (void)earWithFoot:(NSString *)foot{
    NSLog(@"吃%@",foot);
}

- (void)run{
    NSLog(@"跑起来了");
}

+ (void)run{
    NSLog(@"类方法");
}

@end```


- 测试

![Paste_Image.png](https://img.haomeiwen.com/i189984/211e905c33804fde.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)


###使用Runtime进行方法替换

}```

Paste_Image.png

1:第一步 写个url Category

#import <Foundation/Foundation.h>

@interface NSObject (url)

+ (instancetype)JYF_URLWithString:(NSString *)URLString;

@end```


- 第二部分 进行方法交换


import "NSObject+url.h"

import <objc/runtime.h> // 使用Runtime进行方法的交换

@implementation NSObject (url)

// 只要加载这个类 只要参与了加载 就会调用load方法

@end


- 测试


![Paste_Image.png](https://img.haomeiwen.com/i189984/cbc6b83e627ccc84.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

- 方法替换成功!!!



- 降低消耗

###使用Runtime进行方法的懒加载:
那么方法的懒加载用过么?懵逼??
- 怎么去懒加载OC中的方法?

- 先加载一个没有的方法 直接报错后 我们在m文件中进行处理


import "Person.h"

import <objc/message.h>

@implementation Person

// C语言
// 所有的C语言函数都有这两个隐士参数!只要调用 系统都会传递进来!那个对象的那个方法
void eat(id self, SEL _cmd){
NSLog(@"调用了%@对象的%@方法",self,NSStringFromSelector(_cmd));
NSLog(@"哥们吃了");
}

void eat1(id self, SEL _cmd, id obj){
NSLog(@"哥们今晚吃五个%@", obj);
}

// 当这个类被外界调用了没有实现的方法!!!就会来到这里了!!!

@end


- 运行之后
![Paste_Image.png](https://img.haomeiwen.com/i189984/06cb64bcf1cc20ae.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
上一篇 下一篇

猜你喜欢

热点阅读