objective-c协议的默认实现

NSProxy

NSProxy是一个抽象基类,它为一些表现的像是其它对象替身或者并不存在的对象定义API。一般的,发送给代理的消息被转发给一个真实的对象或者代理本身引起加载(或者将本身转换成)一个真实的对象。NSProxy的基类可以被用来透明的转发消息或者耗费巨大的对象的lazy 初始化。
利用NSProxy的代理消息转发功能默认实现协议:

  • InheritProxy
@interface InheritProxy : NSProxy

- (instancetype)initWithObjc:(id)objc;
- (instancetype)initWithObjcs:(NSArray *)objcs;

@end

@interface InheritProxy ()
{
    NSArray *_objcs;
    id _objc;
}
@end

@implementation InheritProxy

- (instancetype)initWithObjc:(id)objc {
    _objc = objc;
    return self;
}

- (instancetype)initWithObjcs:(NSArray *)objcs {
    _objcs = objcs;
    return self;
}

- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel {
    
    for (id objc in _objcs) {
        if ([objc respondsToSelector:sel]) {
            _objc = objc;
            break;
        }
    }
    
    if (_objc != nil) {
        return [_objc methodSignatureForSelector:sel];
    }
    return [super methodSignatureForSelector:sel];
}

- (void)forwardInvocation:(NSInvocation *)invocation {
    if (_objc != nil) {
        [invocation invokeWithTarget:_objc];
    }
}

@end

协议的实现

  • 协议
@protocol AOProtocolOne 
@optional
- (NSString *)name;
@end
  • 实现
@interface AOProtocolOneImpl : NSObject

@end

@implementation AOProtocolOneImpl

- (NSString *)name {
    return @"Json name";
}

@end
  • 用法
@interface TestObject : NSObject
@property (readonly, nonatomic) int age;
@end

@implementation TestObject

- (instancetype)init
{
    self = [super init];
    if (self) {
        AOProtocolOneImpl *impl = [[AOProtocolOneImpl alloc] init];
        InheritProxy *proxy = [[InheritProxy alloc] initWithObjcs:@[self, impl]];
        self = (TestObject *)proxy;
    }
    return self;
}

- (int)age {
    return 100;
}
@end

TestObject *tobj = [[TestObject alloc] init];
NSLog(@"%@, age: %d", tobj.name, tobj.age); //Json name, age: 100
  • 重载方法
- (NSString *)name {
    return @"Lily name";
}
TestObject *tobj = [[TestObject alloc] init];
NSLog(@"%@, age: %d", tobj.name, tobj.age); //Lily name, age: 100

你可能感兴趣的:(objective-c协议的默认实现)