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 
- (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)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 obj = [[DPDynamicProxy alloc] initWithObject:[[DPNormalObject alloc] init]];
    
    [obj doSomething]; //直接调用
    [obj doOtherThing]; // 通过代理调用


输出结果:

 proxy do something

 normal object do something

 normal object do other thing






你可能感兴趣的:(iOS)