iOS-底层原理

NSProxy 的简单介绍和使用

2019-06-14  本文已影响0人  ZJ_偶尔上路

1、首先简单说一下OC消息发送机制

消息发送分两步:

第一步,编译阶段

不带参数:objc_msgSend(receiver,selector)   
带参数:objc_msgSend(recevier,selector,org1,org2,…)

在这一阶段确定消息接受者receiver和要去执行的方法selector,这时候不会去确定方法是否实现。

第二步,运行时阶段

运行时阶段的消息发送的详细步骤如下:

消息转发流程图.png

2、NSProxy的介绍

Apple 官方文档

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 (for example, NSDistantObject) or for lazy instantiation of objects that are expensive to create.
NSProxy 是一个抽象基类,它是为一些作为对象的替身或者并不存在的对象定义的API。一般的,发送给代理的消息被转发给一个真实的对象或者代理本身引起加载(或者将本身转换成)一个真实的对象。NSProxy的基类可以被用来透明的转发消息或者耗费巨大的对象的lazy 初始化。

NSProxy我理解的其实它就是一个消息重定向封装的一个抽象类,类似一个代理人、中间件。可以通过继承它,并重写下面这两个方法来实现消息转发到另一个实例。

- (void)forwardInvocation:(NSInvocation *)invocation;
- (nullable NSMethodSignature *)methodSignatureForSelector:(SEL)sel

3、NSProxy的使用

上一篇 下一篇

猜你喜欢

热点阅读