NSProxy

NSProxy

一、什么是NSProxy

(1)NSProxy是一个抽象的基类,是根类,与NSObject类似;

(2)NSProxy和NSObject都实现了协议;

(3)提供了消息转发的通用接口。

查看NSProxy类:

nsproxy.png

二、NSProxy和NSObject消息传递的异同

1、NSObject消息传递的流程:

(1)NSObject收到消息会先去缓存列表查找SEL,若是找不到,就到自身方法列表中查找,依然找不到就顺着继承链进行查找,依然找不到的话,那就是unknown selector,进入消息转发程序。
(2)调用+(BOOL)resolveInstanceMethod: 其返回值为BOOL类型,表示这个类是否通过class_addMethod新增一个实例方法用以处理该 unknown selector,也就是说在这里可以新增一个处理unknown selector的方法,若不能,则继续往下传递(若unknown selector是类方法,那么调用 +(BOOL)resolveClassMethod:方法)
(3)调用-(id)forwardingTargetForSelector: 这是第二次机会处理unknown selector,即转移给一个能处理unknown selector的其它对象,若返回一个其它的执行对象,那消息从objc_msgSend (id self, SEL op, ...) 重新开始,若不能,则返回nil,并继续向下传递,最后的一次消息处理机会。
(4)调用-(NSMethodSignature *)methodSignatureForSelector: 返回携带参数类型、返回值类型和长度等的selector签名信息 NSMethodSignature对象,Runtime会基于NSMethodSignature实例构建一个NSInvocation对象,作为回调forwardInvocation:的入参。
(5)调用-(void)forwardInvocation:这一步可以对传进来的NSInvocation进行一些操作,把尚未处理的消息有关的全部细节都封装在NSInvocation中,包括selector,目标(target)和参数等。

2、NSProxy消息传递的流程:

(1)接收到unknown selector后,直接回调methodSignatureForSelector:方法,返回携带参数类型、返回值类型和长度等的selector签名信息 NSMethodSignature对象,Runtime会基于NSMethodSignature实例构建一个NSInvocation对象,作为回调forwardInvocation:的入参。
(2)调用-(void)forwardInvocation:这一步可以对传进来的NSInvocation进行一些操作,把尚未处理的消息有关的全部细节都封装在NSInvocation中,包括selector,目标(target)和参数等。

三、NSProxy用法

1、实现多继承

场景:西红柿作为一种常见的食物,既是水果又是蔬菜。用程序语言来说,西红柿类应当既继承水果类,又继承蔬菜类,但是在OC中只有单继承,如何模拟实现多继承呢?

首先,实现Fruit和Vegetable类:

########水果类#########
////水果类:Fruit.h
@protocol FruitProtocol 
@property (nonatomic, copy) NSString *texture;
@property (nonatomic, copy) NSString *name;
- (void)fruitDesc;
@end

@interface Fruit : NSObject
@end

////水果类:Fruit.m
@interface Fruit() 
@end

@implementation Fruit
//告诉编译器、texture属性的setter、getter方法由编译器来生成、同时用_texture来合成成员变量
@synthesize texture = _texture;
@synthesize name = _name;

- (void)fruitDesc
{
    NSLog(@"%@,作为水果能够促进消化。口感:%@", _name, _texture);
}
@end


########蔬菜类#########
////蔬菜类:Vegetable.h
@protocol VegatableProtocol 
@property (nonatomic, copy) NSString *anotherName;
- (void)vegetableDesc;
@end

@interface Vegetable : NSObject
@end

////蔬菜类:Vegetable.m
@interface Vegetable() 
@end

@implementation Vegetable
@synthesize anotherName = _anotherName;

- (void)vegetableDesc
{
    NSLog(@"%@,作为蔬菜可提供多种维生素。", _anotherName);
}
@end

其次,让代理TomatoProxy类遵循协议。通过重写forwardInvocation:和methodSignatureForSelector:方法将消息转给TomatoProxy类来响应。methodSignatureForSelector:方法,返回的是一个NSMethodSignature类型,来描述给定selector的参数和返回值类型。返回nil,表示proxy不能识别指定的selector。forwardInvocation:方法将消息转发到对应的对象上。

########西红柿类#########
////TomatoProxy.h
@interface TomatoProxy : NSProxy 
+ (instancetype)tomatoProxy;
@end

////TomatoProxy.m
@implementation TomatoProxy
{
    Fruit *_fruit;
    Vegetable *_vegetable;
    NSMutableDictionary *_targetMethodsHashMap;
}

+ (instancetype)tomatoProxy
{
    return [[TomatoProxy alloc] init];
}

//创建init方法
- (instancetype)init
{
    //初始化需要代理的对象(target),和存储对象方法的哈希表
    _targetMethodsHashMap = @{}.mutableCopy;
    _fruit = [[Fruit alloc] init];
    _vegetable = [[Vegetable alloc] init];
    
    [self registerMethodsForTarget:_fruit];
    [self registerMethodsForTarget:_vegetable];
    
    return self;
}

- (void)forwardInvocation:(NSInvocation *)invocation
{
    SEL aSel = invocation.selector;
    NSString *methodKey = NSStringFromSelector(aSel);
    id targetObject = _targetMethodsHashMap[methodKey];
    if (targetObject && [targetObject respondsToSelector:aSel]) {
        [invocation invokeWithTarget:targetObject];
    }
}

- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel
{
    NSString *methodName = NSStringFromSelector(sel);
    id targetObject = _targetMethodsHashMap[methodName];
    if (targetObject && [targetObject respondsToSelector:sel]) {
        return [targetObject methodSignatureForSelector:sel];
    }
    return nil;
}

/**
 将目标对象的所有方法添加到哈希表中
 @param aTarget 目标对象
 key 方法名
 value 对象地址
 */
- (void)registerMethodsForTarget:(id)aTarget
{
    unsigned int count = 0;
    Method *methodList = class_copyMethodList([aTarget class], &count);
    
    for(int i = 0; i < count; i++) {
        Method aMethod = methodList[i];
        SEL aSel = method_getName(aMethod);
        const char *methodName = sel_getName(aSel);
        [_targetMethodsHashMap setObject:aTarget forKey:[NSString stringWithUTF8String:methodName]];
    }
    free(methodList);
}

@end

最后,在main函数中就可以通过TomatoProxy类访问Fruit类和Vegetable类的属性和方法了。

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // 1、使用NSProxy模拟多继承。
        // TomatoProxy同时可以具备Fruit和Vegetable类的特性
        TomatoProxy *tomato = [TomatoProxy tomatoProxy];
        //设置Fruit类的属性,调用Fruit类的方法
        tomato.name = @"西红柿";
        tomato.texture = @"酸酸甜甜";
        [tomato fruitDesc];
        //设置vegetable类的属性,调用vegetable类的方法
        tomato.anotherName = @"番茄";
        [tomato vegetableDesc];
    }
    return 0;
}

//打印结果:
2019-03-21 15:34:15.247663+0800 NSProxyTest[44704:13499339] 西红柿,作为水果能够促进消化。口感:酸酸甜甜
2019-03-21 15:38:04.690131+0800 NSProxyTest[44704:13499339] 番茄,作为蔬菜可提供多种维生素

2、利用NSProxy解决NSTimer循环引用

//SecondViewController.m
@interface SecondViewController ()
@property (nonatomic, strong) NSTimer *timer;
@end

@implementation SecondViewController
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self startTimer];
}
- (void)startTimer
{
    self.timer = [NSTimer timerWithTimeInterval:3.0
                                         target:self
                                       selector:@selector(timerInvoked:)
                                       userInfo:nil
                                        repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}
- (void)timerInvoked:(NSTimer *)timer
{
    NSLog(@"======== timer ========");
}
- (void)dealloc
{
    [self.timer invalidate];
    self.timer = nil;
    NSLog(@"SecondViewController dealloc");
}
@end

上面代码中,从ViewController push到SecondViewController之后,开启一个定时器,当页面pop回ViewController之后,定时器未被销毁。其原因如下图所示:

timer_cycle.png

稍作修改:

////TimerWeakProxy.h
@interface TimerWeakProxy : NSProxy
/**
 创建代理对象
 @param target 被代理的对象
 @return 代理对象
 */
+ (instancetype)proxyWithTarget:(id)target;
@end

////TimerWeakProxy.m
@interface TimerWeakProxy ()
@property (weak, nonatomic, readonly) id target; //被代理的对象为weak
@end

@implementation TimerWeakProxy
+ (instancetype)proxyWithTarget:(id)target
{
    return [[self alloc] initWithTarget:target];
}
- (instancetype)initWithTarget:(id)target
{
    _target = target;
    return self;
}
- (void)forwardInvocation:(NSInvocation *)invocation
{
    SEL sel = [invocation selector];
    if (_target && [_target respondsToSelector:sel]) {
        [invocation invokeWithTarget:_target];
    }
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
{
    return [_target methodSignatureForSelector:aSelector];
}
@end

////SecondViewController.m
- (void)startTimer
{
    self.timer = [NSTimer timerWithTimeInterval:3.0
                                         target:[TimerWeakProxy proxyWithTarget:self]
                                       selector:@selector(timerInvoked:)
                                       userInfo:nil
                                        repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}
weakProxy_timer.png

3、实现协议分发器(一对多代理)

在OC中,delegate一般用于对象之间一对一的通信,但是有时候我们希望可以有多个对象同时响应一个protocol。基于这种需求我们可以利用NSProxy实现一个消息分发器,将protocol中需要实现的方法交由分发器转发给多个遵循protocol的对象,从而实现一对多的delegate。

一对一delegate的工作模式:

one_to_one_delegate.png

协议分发器的工作模式:

one_to_multi_delegate.png

简言之,第一步:将需要遵循的protocol及遵循该protocol的对象交由分发器;第二步:分发器将消息转发给可以响应protocol中方法的多个delegate对象;第三步:每个delegate对象分别实现protocol中声明的方法。

协议分发器的实现:

// 定义一个方法
//struct objc_method_description {
//SEL _Nullable name;               /**< The name of the method */
//char * _Nullable types;           /**< The types of the method arguments */
//};
//protocol_getMethodDescription: 为指定的method或者protocol返回一个method description structure
//protocol_getMethodDescription(Protocol * _Nonnull proto, SEL _Nonnull aSel, BOOL isRequiredMethod, BOOL isInstanceMethod)
//
struct objc_method_description MethodDescriptionForSelWithProtocol(Protocol *aProtocol, SEL aSel)
{
    struct objc_method_description desc = protocol_getMethodDescription(aProtocol, aSel, YES, YES);
    if (desc.types) {
        return desc;
    }
    desc = protocol_getMethodDescription(aProtocol, aSel, NO, YES);
    if (desc.types) {
        return desc;
    }
    return (struct objc_method_description) {NULL, NULL};
};

// 判断selector是否属于某一Protocol
BOOL ProtocolContainsSelector(Protocol *aProtocol, SEL aSel)
{
    return MethodDescriptionForSelWithProtocol(aProtocol, aSel).types ? YES : NO;
}

//*********** 协议消息转发器 ***********//
@interface ProtocolMessageDispatcher ()
@property (nonatomic, strong) Protocol *prococol; //协议
@property (nonatomic, strong) NSArray *targets; //协议实现者对象(多个)
@end

@implementation ProtocolMessageDispatcher

+ (id)dispatchProtocol:(Protocol *)aProtocol withTargets:(NSArray *)theTargets
{
    return [[ProtocolMessageDispatcher alloc] initWithProtocol:aProtocol withTargets:theTargets];
}

- (instancetype)initWithProtocol:(Protocol *)aProtocol withTargets:(NSArray *)theTargets
{
    self.prococol = aProtocol;
    NSMutableArray *valideObjects = @[].mutableCopy;
    for (id object in theTargets) {
        if ([object conformsToProtocol:aProtocol]) {
            objc_setAssociatedObject(object, _cmd, self, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
            [valideObjects addObject:object];
        }
    }
    self.targets = valideObjects.copy;
    return self;
}

- (BOOL)respondsToSelector:(SEL)aSelector
{
    if (!ProtocolContainsSelector(self.prococol, aSelector)) {
        return [super respondsToSelector:aSelector];
    }
    for (id object in self.targets) {
        if ([object respondsToSelector:aSelector]) {
            return YES;
        }
    }
    return NO;
}

/*
返回携带参数类型、返回值类型和长度等的selector签名信息 NSMethodSignature对象,Runtime会基于NSMethodSignature实例构建一个NSInvocation对象,作为回调forwardInvocation:的入参
*/
- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel
{
    if (!ProtocolContainsSelector(self.prococol, sel)) {
        return [super methodSignatureForSelector:sel];
    }
    struct objc_method_description methodDesc = MethodDescriptionForSelWithProtocol(self.prococol, sel);
    return [NSMethodSignature signatureWithObjCTypes:methodDesc.types];
}

/*
这一步可以对传进来的NSInvocation进行一些操作,把尚未处理的消息有关的全部细节都封装在NSInvocation中,包括selector,目标(target)和参数等
*/
- (void)forwardInvocation:(NSInvocation *)invocation
{
    SEL aSel = invocation.selector;
    if (!ProtocolContainsSelector(self.prococol, aSel)) {
        [super forwardInvocation:invocation];
        return;
    }
    for (id object in self.targets) {
        if ([object respondsToSelector:aSel]) {
            [invocation invokeWithTarget:object]; //object是最后真正处理invocation的对象
        }
    }
}

使用协议分发器:

/// self和TableDelegate都成为tableView的代理
/// 当点击cell时 self和TableDelegate中的方法都会被调用
self.tableView.delegate = [ProtocolMessageDispatcher dispatchProtocol:@protocol(UITableViewDelegate) withTargets:@[self, [TableDelegate new]]];

///点击cell时,两个delegate对象的方法都会执行:
2019-04-03 17:02:31.733479+0800 NSProxyDemo[42445:13711860] -[DispatchMessageController tableView:didSelectRowAtIndexPath:]
2019-04-03 17:02:31.733687+0800 NSProxyDemo[42445:13711860] -[TableDelegate tableView:didSelectRowAtIndexPath:]

参考资料:

https://developer.apple.com/library/archive/samplecode/ForwardInvocation/Listings/main_m.html#//apple_ref/doc/uid/DTS40008833-main_m-DontLinkElementID_4
http://yehuanwen.github.io/2016/10/18/nsproxy/
http://www.olinone.com/?p=643
https://www.jianshu.com/p/8e700673202b
https://www.jianshu.com/p/b0f5fd3e4b7c
http://ggghub.com/2016/05/11/%E5%88%A9%E7%94%A8NSProxy%E8%A7%A3%E5%86%B3NSTimer%E5%86%85%E5%AD%98%E6%B3%84%E6%BC%8F%E9%97%AE%E9%A2%98/
NSProxy和NSObject:https://www.jianshu.com/p/5bfcc32c21c0
NSProxy与UIKit框架:https://mazyod.com/blog/2014/03/10/nsproxy-with-uikit/#Enter-the-NSProxy-Class
NSProxy与KVO:https://stackoverflow.com/questions/9054970/nsproxy-and-key-value-observing

你可能感兴趣的:(NSProxy)