NSProxy简介以及使用

简介

Objective-C中,大部分类都是继承自NSObject,但它并不是唯一的root class,还有一个就是NSProxy这个类,看一下API中它的介绍:

NSProxy is an abstract superclass defining an API for objects that act as stand-ins for other objects or for objects that don’t exist yet. Typically, a message to a proxy is forwarded to the real object or causes the proxy to load (or transform itself into) the real object. Subclasses of NSProxy can be used to implement transparent distributed messaging or for lazy instantiation of objects that are expensive to create.
NSProxy implements the basic methods required of a root class, including those defined in the NSObject protocol. However, as an abstract class it doesn’t provide an initialization method, and it raises an exception upon receiving any message it doesn’t respond to. A concrete subclass must therefore provide an initialization or creation method and override the forwardInvocation: and methodSignatureForSelector: methods to handle messages that it doesn’t implement itself. A subclass’s implementation of forwardInvocation: should do whatever is needed to process the invocation, such as forwarding the invocation over the network or loading the real object and passing it the invocation. methodSignatureForSelector: is required to provide argument type information for a given message; a subclass’s implementation should be able to determine the argument types for the messages it needs to forward and should construct an NSMethodSignature object accordingly. See the NSDistantObject , NSInvocation, and NSMethodSignature class specifications for more information.

简单来说:

  1. NSProxy是一个抽象基类, 主要是 stand-ins, 用于消息转发, 使用时需要子类化
  2. 这个类没有指定初始化方法, 子类化之后必须提供初始化方法,
  3. 使用时候需要实现基类以及NSObject协议的一些方法,forwardInvocation:``methodSignatureForSelector:, 这两个方法需要重载

使用

上文可以看到, 这个类主要是在消息转发中扮演一个中间人的角色,实际项目中,看到的应用重要有这些:

  1. 实现一个weak proxy, 防止retain cycle, 这里有一份实现的代码:YYTextWeakProxy.m, 使用这个类, 可以在调用NSTimer等的时候让timer保留一个weak reference, 从源码中可以看到,定义了@property (nullable, nonatomic, weak, readonly) id target;, 这个target在初始化方法中对传入的对象弱引用,并实现respondsToSelector:, weak对象调用方法之前都会先调用这个方法,如果被释放掉的话就不会执行接下来的方法调用,从而实现weak proxy.
  2. 实现多继承
    NSProxy——少见却神奇的类, 这篇文件介绍了使用NSProxy实现多继承的一种方法.
  3. 其他一些实践,比如有人做AOP用到它,链接地址用 NSProxy 实现面向切面编程,NSProxy实现AOP方便为iOS应用实现异常处理策略