-
Notifications
You must be signed in to change notification settings - Fork 766
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
f5c6931
commit 05cbfc7
Showing
1 changed file
with
50 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
|
||
|
||
|