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






0 0
原创粉丝点击