NSMethodSignature 和 NSInvocation #13
onnttf
started this conversation in
Show and tell
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
常见的调用方法的两种方式
performSelector: withObject:
优点: 可以调用运行时添加方法
缺点: 在编译阶段不会做校验。只有在程序运行的时候,才会知道是否存在即将调用的方法,如果方法不存在,程序会崩溃。因此为了保证程序的健壮,在调用方法前应该使用
- (BOOL)respondsToSelector:(SEL)aSelector
,检查方法是否实现。直接调用方法
优点: 在编译阶段就会教研方法是否存在,Xcode 会有相应提示
缺点: 局限性大,如果想调用某个方法,必须先实现这个方法,不如
performSelector: withObject:
灵活。使用 NSMethodSignature 和 NSInvocation 调用方法
使用
NSMethodSignature
和NSInvocation
组合实现方法的调用。NSMethodSignature
通过
NSMethodSignature
可以获取方法的参数类型和返回值类型。常用方法有:可以通过下面的代码,更好的理解该怎么获取方法签名:
NSInvocation
NSInvocation
可以说是performSelector: withObject:
的升级版,可以调用较为复杂的方法,进行参数、返回值的处理等;NSMethodSignature 和 NSInvocation 搭配的使用方法
Beta Was this translation helpful? Give feedback.
All reactions