Skip to content

Commit

Permalink
Runtime消息解析
Browse files Browse the repository at this point in the history
  • Loading branch information
liberalisman committed Sep 27, 2020
1 parent f5c6931 commit 05cbfc7
Showing 1 changed file with 50 additions and 2 deletions.
52 changes: 50 additions & 2 deletions Runtime/15.第十五题.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,54 @@
## 15.说一下 `Runtime` 消息解析和转发
## 15. `Runtime` 消息解析

如果当前类没有对应的实例方法,系统会调用如下方法,可以选择在这个时机动态添加

```objc
+(BOOL)resolveInstanceMethod:(SEL)sel {

if (sel == @selector(eat)) {
class_addMethod([self class], sel, (IMP)vc_eat, "v@:");
return YES;
}
return [super resolveInstanceMethod:sel];
}
```

```objc
void vc_eat(id obj,SEL _cmd) {
NSLog(@"这是Eat方法");
}
```
如果当前类没有对应的类方法,系统会调用如下方法,可以选择在这个时机动态添加
```objc
+(BOOL) resolveClassMethod:(SEL)sel {
if(sel == @selector(newPerson)) {
// 找到当前类的 metaClass
Class MetaClass = objc_getMetaClass([NSStringFromClass(self) UTF8String]);
class_addMethod(MetaClass,sel,(IMP)vc_newPerson,"v@:");
return YES;
}
return [super resolveClassMethod:sel];
}
```

```objc
void vc_newPerson(id obj,SEL _cmd) {
NSLog(@"当前是类方法 newPerson");
}
```
如果在当前类,以上两个方法都没有实现,可以将消息转发给其他的类处理
```objc
- (id)forwardingTargetForSelector:(SEL)aSelector {
if(aSelector == @selector(someMethod)) {
return [SomeClass new];
}
return [super forwardingTargetForSelector:aSelector];
}
```

![](http://okhqmtd8q.bkt.clouddn.com/%E6%B6%88%E6%81%AF%E8%BD%AC%E5%8F%91.png)



0 comments on commit 05cbfc7

Please sign in to comment.