解密NSproxy的面纱

 NSProxyDemo该文章介绍NSProxy这个类。 先给代码地址:

NSProxyDemo

在我理解,主要是一个中介类。

 比如我想去卖衣服那里买衣服,我想卖书那里去买书。又不想亲自去,就找个代理一起完成。

 SLJBookProvider 是书的提供者。

 SLJClothesProvider是衣服的提供者。

 SLJDealerProxy这个类就是衣服的代理类。继承自NSProxy这个类。

是一个虚类;你可以通过继承它,并重写这两个方法以实现消息转发到另一个实例这个类有两个方法

 - (void)forwardInvocation:(NSInvocation *)anInvocation;

 - (NSMethodSignature *)methodSignatureForSelector:(SEL)sel; 

 重写- (void)forwardInvocation:(NSInvocation *)anInvocation,这是NSObject用来在本身不能响应selector时向其他类传递调用时用到的。

forwardInvocation:。methodSignatureForSelector:的作用在于为另一个类实现的消息创建一个有效的方法签名,必须实现,并且返回不为空的methodSignature,否则会crash。 

SLJDealerProxy重写了这两个类。

//这个方法获取了两个类所有的方法名。

 -(void)_registerMethodsWithTarget:(id)target{

             unsigned int numerOfMethods = 0; 

             Method *method_list = class_copyMethodList([target class], &numerOfMethods);

             for (int i = 0; i < numerOfMethods; i++) { 

 Method temp_method = method_list[i]; 

 SEL temp_sel = method_getName(temp_method); 

 const char *temp_method_name = sel_getName(temp_sel);

 [_methodsMap setObject:target forKey:[NSString stringWithUTF8String:temp_method_name]]; 

 }

 free(method_list); 

}

 #pragma mark - NSProtxy override methods

 -(void)forwardInvocation:(NSInvocation *)invocation{ 

 SEL sel = invocation.selector;

 NSString *methodName = NSStringFromSelector(sel);

 id target = _methodsMap[methodName]; 

 if (target && [target respondsToSelector:sel]) {

 [invocation invokeWithTarget:target];

 }else{

 [super forwardInvocation:invocation];

 }

 }

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 转至元数据结尾创建: 董潇伟,最新修改于: 十二月 23, 2016 转至元数据起始第一章:isa和Class一....
    40c0490e5268阅读 1,789评论 0 9
  • 我们常常会听说 Objective-C 是一门动态语言,那么这个「动态」表现在哪呢?我想最主要的表现就是 Obje...
    Ethan_Struggle阅读 2,232评论 0 7
  • ping怎么这么高? 什么是Runtime? 这还要说?run( 运行)、time(时),runtime(运行时)...
    大大盆子阅读 663评论 1 1
  • 转载:http://yulingtianxia.com/blog/2014/11/05/objective-c-r...
    F麦子阅读 772评论 0 2
  • 本文转载自:http://yulingtianxia.com/blog/2014/11/05/objective-...
    ant_flex阅读 799评论 0 1