NSProxy的简单使用

平时开发中我们使用的大部分类的基类都是NSObject,今天介绍另一个基类——NSProxy。
先来看一下苹果官方文档:

NSProxy

An abstract superclass defining an API for objects that act as stand-ins for other objects or for objects that don’t exist yet.
好的,我们知道了他是一个抽象类。
再往下

Overview

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
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.
原来,它的作用是一个映射,通过定义子类,并重写

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

这两个方法来实现将消息转发给真正的对象。我们知道OC不支持多继承,通过NSProxy,就可以模拟实现多继承。那么现在,NSProxy怎么用呢?

假设现在有这样一个需求:
我们已经将项目中的网络接口进行了模块化,将不同模块下的接口放在了不同的文件中。当我们想调用不同模块下的接口时,想要通过一个统一的映射来调用,现在我们来写这个映射。
首先,我们来创建两个接口模块。
商品模块:

@protocol ProductServiceProtocel <NSObject>
- (void)getProductInfo:(NSString *)productSkn;
@end

@interface ProductService : NSObject
@end

以及订单模块:

@protocol OrderServiceProtocel <NSObject>
- (void)submitOrder:(NSString *)prodcutName;
@end

@interface OrderService : NSObject
@end
注意:这里的接口声明要写在protocol中,然后让我们的proxy遵循这两个协议,用来骗过编译器。

然后我们实现这两个接口模块:

@implementation ProductService
- (void)getProductInfo:(NSString *)productSkn {
    NSLog(@"我是一件程序员标配的横条纹T,我的skn是%@",productSkn);
}
@end
@implementation OrderService
- (void)submitOrder:(NSString *)prodcutName {
    NSLog(@"我买了一件%@",prodcutName);
}
@end

现在我们来写我们的映射。

#import <Foundation/Foundation.h>
#import "ProductService.h"
#import "OrderService.h"

@interface ServiceProxy : NSProxy <ProductServiceProtocel, OrderServiceProtocel>
+ (ServiceProxy *)shareProxy;
@end

NSProxy是一个抽象类,系统不提供init方法,所以需要我们自己实现。

#import "ServiceProxy.h"
#import <objc/runtime.h>

@implementation ServiceProxy
{
    ProductService *_product;
    OrderService *_order;
    NSMutableDictionary *_targetProxy;
}

#pragma class method
+ (ServiceProxy *)shareProxy {
    return [[ServiceProxy alloc] init];
}

#pragma init
- (ServiceProxy *)init {
    _targetProxy = [NSMutableDictionary dictionary];
    _product = [[ProductService alloc] init];
    _order = [[OrderService alloc] init];
    
    [self _registerMethodsWithTarget:_product];
    [self _registerMethodsWithTarget:_order];
    
    return self;
}

在init方法中,初始化成员变量已经将各接口模块中的方法以及对象映射在一个字典中。

#pragma private
- (void)_registerMethodsWithTarget:(id)target {
    unsigned int methodsNum = 0;
    
    Method *methodList = class_copyMethodList([target class], &methodsNum);
    for (int i = 0; i < methodsNum; i++) {
        Method method = methodList[i];
        SEL temp_sel = method_getName(method);
        const char *temp_method_name = sel_getName(temp_sel);
        [_targetProxy setObject:target forKey:[NSString stringWithUTF8String:temp_method_name]];
    }
    
    free(methodList);
}

接下来就可以重写系统提供的两个方法,根据方法名从我们的映射字典中找到对应的target,然后执行。

#pragma override
- (void)forwardInvocation:(NSInvocation *)invocation {
    SEL selector = invocation.selector;
    NSString *methodName = NSStringFromSelector(selector);
    id target = _targetProxy[methodName];
    if (target && [target respondsToSelector:selector]) {
        [invocation invokeWithTarget:target];
    }else {
        [super forwardInvocation:invocation];
    }
}

- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel {
    NSString *methodName = NSStringFromSelector(sel);
    id target = _targetProxy[methodName];
    if (target && [target respondsToSelector:sel]) {
        return [target methodSignatureForSelector:sel];
    }else {
        return [super methodSignatureForSelector:sel];
    }
}

现在服务映射就写完了,在控制器中来调动接口:

ServiceProxy *proxy = [ServiceProxy shareProxy];
[proxy getProductInfo:@"123456"];
[proxy submitOrder:@"程序员标配的横条纹T"];

最终的执行结果:demo

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

推荐阅读更多精彩内容