nspoxy

  • NSProxy是苹果官方推荐专门用来做消息转发的,内部有一个target属性,定位更加精准,效率非常高;
  • NSProxy 跳过了消息转发的流程, 即本类/父类 方法缓存和方法列表中遍历查询方法的过程, 直接调用方法签名, 因此高效
  • NSProxy和NSObject是同一个级别的类,都是基类, NSproxy 没有子类
  • 注意forwardingTargetForSelector此方法被注释, 虽然使用它同样也可以实现消息转发, 但是使用它同样会走消息转发流程, 因此不推荐
@interface NSProxy <NSObject> {
    __ptrauth_objc_isa_pointer Class    isa;
}

+ (id)alloc;// 注意区别nsobject没有init方法
+ (id)allocWithZone:(nullable NSZone *)zone NS_AUTOMATED_REFCOUNT_UNAVAILABLE;
+ (Class)class;

- (void)forwardInvocation:(NSInvocation *)invocation;
- (nullable NSMethodSignature *)methodSignatureForSelector:(SEL)sel NS_SWIFT_UNAVAILABLE("NSInvocation and related APIs not available");
- (void)dealloc;
- (void)finalize;
@property (readonly, copy) NSString *description;
@property (readonly, copy) NSString *debugDescription;
+ (BOOL)respondsToSelector:(SEL)aSelector;

- (BOOL)allowsWeakReference API_UNAVAILABLE(macos, ios, watchos, tvos);
- (BOOL)retainWeakReference API_UNAVAILABLE(macos, ios, watchos, tvos);

// - (id)forwardingTargetForSelector:(SEL)aSelector;

@end

正确的nspoxy实现方式, 使用方法签名完成消息转发

//消息转发到target

//返回方法签名
- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel
{
    return [self.target methodSignatureForSelector:sel];
}

//内部实现方法调用
- (void)forwardInvocation:(NSInvocation *)invocation
{
    [invocation invokeWithTarget:self.target];
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 了解Runtime有助于我们理解Objective-C运行时系统的工作原理以及如何利用它。本章将介绍NSObjec...
    新生代农民工No1阅读 782评论 0 1
  • 《Effective Objective-C 2.0:编写高质量iOS与OS X代码的52个有效方法》 在看这本书...
    monkey姜啦阅读 1,466评论 0 3
  • 转至元数据结尾创建: 董潇伟,最新修改于: 十二月 23, 2016 转至元数据起始第一章:isa和Class一....
    40c0490e5268阅读 1,858评论 0 9
  • 牛犊子们好,我是shark, 老规矩,上问题,搞懵逼你们 1: 咋滚动下UI定时器就不起效了?2: NSTime...
    谌文阅读 883评论 0 0
  • 一、简介 C++ 是基于静态类型,而 Objective-C 是基于动态运行时类型。用 C++ 编写的程序通过编译...
    和风细羽阅读 381评论 0 1