NSProxy的使用

用的案例代码是网上其他资源的,主要是NSProxy的子类和场景类中的一点说明

抄书的一段:NSProxy的作用是为其他对象的替身对象定义一个API。发给代理对象的消息会被转发给实体对象,或者让代理加载实体对象或吧代理自身变成实体对象

There are two instance methods that are essential to make thewhole proxy deal happen, forwardInvocation: and methodSignatureForSelector:

AnNSProxy subclass 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 a NSProxy subclass doesn’t respond to a method that would be available to a realobject, then the Objective-C runtime will send a message of methodSignatureForSelector: 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 of NSInvocation and send it with a forwardInvocation: message to the proxy object so it will forward the invocation to other object.

 If the proxy object of NSProxy’ssubclass can respond to the message, then the forwardInvocation: 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值