NSProxy的使用
来源:互联网 发布:linux查看文件目录命令 编辑:程序博客网 时间:2024/06/15 14:29
用的案例代码是网上其他资源的,主要是NSProxy的子类和场景类中的一点说明
抄书的一段:NSProxy的作用是为其他对象的替身对象定义一个API。发给代理对象的消息会被转发给实体对象,或者让代理加载实体对象或吧代理自身变成实体对象
There are two instance methods that are essential to make thewhole proxy deal happen,forwardInvocation:and methodSignatureForSelector:.
AnNSProxysubclass doesn’t even need to have other extra methods except, probably, aninitialization method and some other useful properties.
The key is that when an object of aNSProxysubclass doesn’t respond to a method that would be available to a realobject, thenthe Objective-C runtime will send a message ofmethodSignatureForSelector:to the proxy object for a correct method signature of the message being forwarded.
The runtime will in turn use the returned method signature to construct aninstance ofNSInvocationand send it with aforwardInvocation:message to the proxy object so it will forward the invocation to other object.
If the proxy object ofNSProxy’ssubclass can respond to the message, then theforwardInvocation:method will not beinvoked at all.
上代码
@protocol DPDynamicProtocol <NSObject>- (void) doSomething;- (void) doOtherThing;@end
@implementation DPNormalObject-(void)doSomething{ NSLog(@"normal object do something");}-(void)doOtherThing{ NSLog(@"normal object do other thing");}
@implementation DPDynamicProxy-(instancetype)initWithObject:(id<DPDynamicProtocol>)obj{ self.obj = obj; return self; }- (void) forwardInvocation:(NSInvocation *)invocation{ if(self.obj){ [invocation setTarget:self.obj]; [invocation invoke]; }}-(NSMethodSignature *)methodSignatureForSelector:(SEL)sel{ if([self.obj isKindOfClass:[NSObject class]]){ return [(NSObject *)self.obj methodSignatureForSelector:sel]; } return [super methodSignatureForSelector:sel];}-(void)doSomething{ NSLog(@"proxy do something"); [self.obj doSomething];}
场景类:
id<DPDynamicProtocol> obj = [[DPDynamicProxy alloc] initWithObject:[[DPNormalObject alloc] init]]; [obj doSomething]; //直接调用 [obj doOtherThing]; // 通过代理调用
proxy do something
normal object do something
normal object do other thing
- NSProxy的使用
- NSProxy的使用
- 使用NSProxy和NSObject设计代理类的差异
- 使用NSProxy和NSObject设计代理类的差异
- 关于NSProxy的理解
- NSProxy
- NSProxy
- 使用NSProxy实现代理模式
- [iOS]使用NSProxy实现代理模式
- [iOS]使用NSProxy实现消息转发机制,模拟多重继承
- [iOS]使用NSProxy实现消息转发机制,模拟多重继承
- [iOS]使用NSProxy实现消息转发机制,模拟多重继承
- 使用NSProxy实现消息转发机制,模拟多重继承
- 利用NSProxy做NSTmer和CADisplayLink的target
- NSProxy——少见却神奇的类
- NSProxy——少见却神奇的类
- NSProxy 详解
- NSProxy学习
- 小学奥赛求阴影面积,待解
- webSocket在微信中崩溃的解决方案
- win7 pyspider安装部署常见问题
- 51 nod 1009 数字1的数量
- Android GradientDrawable的XML实现
- NSProxy的使用
- socket实现服务器与客户端通信
- java服务端接受安卓bitmap图片编码问题
- ABAP Function中Export和Import参数和程序中是相反的
- 自定义下拉刷新控件-仿美团刷新效果
- Ubuntu 16.04 update error
- Spring Data Jpa简化Jpa开发
- ThreadLocal的理解
- java 中文和Unicode码 互相转换