NSProxy

NSProxy

一、什么是NSProxy

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

(2)NSProxy和NSObject都实现了<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 <NSObject>
@property (nonatomic, copy) NSString *texture;
@property (nonatomic, copy) NSString *name;
- (void)fruitDesc;
@end

@interface Fruit : NSObject
@end

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

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

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


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

@interface Vegetable : NSObject
@end

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

@implementation Vegetable
@synthesize anotherName = _anotherName;

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

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

########西红柿类#########
////TomatoProxy.h
@interface TomatoProxy : NSProxy <FruitProtocol, VegatableProtocol>
+ (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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 220,809评论 6 513
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,189评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 167,290评论 0 359
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,399评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,425评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,116评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,710评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,629评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,155评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,261评论 3 339
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,399评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,068评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,758评论 3 332
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,252评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,381评论 1 271
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,747评论 3 375
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,402评论 2 358

推荐阅读更多精彩内容

  • 前言 OC中类是不支持多继承的,一个类只有一个父类, 这就是单一继承,但是我们可以用协议protocol和 NSP...
    小盟城主阅读 708评论 0 0
  •   最近准备进一步重构某几个页面,从结构上讲用的是 MVVM,较为清晰明了,同时也不至于所有代码都集中在 UIVi...
    盲果冻阅读 3,641评论 2 7
  • 一、来自官方文档的介绍 一个抽象的超类,它定义了对象的API,充当其他对象或不存在的对象的替身。通常,将消息发送到...
    oneday527阅读 630评论 0 1
  • NSProxyDemo该文章介绍NSProxy这个类。 先给代码地址: NSProxyDemo 在我理解,主要是一...
    _苏丽君_阅读 320评论 0 0
  • 2018年十月一号,结婚4周年。不同于以往的纪念日,老公送我个小礼物,我们两个人出去吃一顿有格调的晚餐或者午餐。今...
    木易小妮阅读 422评论 1 0