- NSProxy是蘋果官方推薦專門用來做消息轉(zhuǎn)發(fā)的,內(nèi)部有一個target屬性,定位更加精準,效率非常高;
- NSProxy 跳過了消息轉(zhuǎn)發(fā)的流程, 即本類/父類 方法緩存和方法列表中遍歷查詢方法的過程, 直接調(diào)用方法簽名, 因此高效
- NSProxy和NSObject是同一個級別的類,都是基類, NSproxy 沒有子類
- 注意forwardingTargetForSelector此方法被注釋, 雖然使用它同樣也可以實現(xiàn)消息轉(zhuǎn)發(fā), 但是使用它同樣會走消息轉(zhuǎn)發(fā)流程, 因此不推薦
@interface NSProxy <NSObject> {
__ptrauth_objc_isa_pointer Class isa;
}
+ (id)alloc;// 注意區(qū)別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實現(xiàn)方式, 使用方法簽名完成消息轉(zhuǎn)發(fā)
//消息轉(zhuǎn)發(fā)到target
//返回方法簽名
- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel
{
return [self.target methodSignatureForSelector:sel];
}
//內(nèi)部實現(xiàn)方法調(diào)用
- (void)forwardInvocation:(NSInvocation *)invocation
{
[invocation invokeWithTarget:self.target];
}