刚刚看到一篇文章介绍的是关于iOS多继承的实现,作者也是用NSProxy实现,但是和我之前的有些不一样,在这里做个补充。
作者的思路也是创建一个NSProxy的类,但是给他设置一个暴露出来的属性和一个转换类型的方法,
@interface Person : NSObject
@property (nonatomic,copy)NSString *name;
@end
#import "Person.h"
@implementation Person
- (void)eat{
NSLog(@"%@在吃饭",self.name);
}
@end
@interface Student : NSObject
@property (nonatomic,copy)NSString *studentNo;
@end
@implementation Student
- (void)study{
NSLog(@"好好学习");
}
@end
@interface WJProxy : NSProxy
@property (nonatomic,strong) NSObject *object;
- (id)transformToObject:(NSObject *)object;
@end
#import "WJProxy.h"
@implementation WJProxy
- (id)transformToObject:(NSObject *)object{
self.object = object;
return self.object;
}
// 当然这里的消息的标准转发也可以用之前把类的方法名都放在一个字典里,通过判断当前类是否响应要执行的方法,执行转发的流程。
- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel{
NSMethodSignature *signature ;
if(self.object){
signature = [self.object methodSignatureForSelector:sel];
}else{
signature = [super methodSignatureForSelector:sel];
}
return signature;
}
- (void)forwardInvocation:(NSInvocation *)invocation{
if(self.object){
[invocation setTarget:self.object];
[invocation invoke];
}
}
@end
- (void)viewDidLoad {
[super viewDidLoad];
/*DealerProxy *proxy = [DealerProxy dealerProxy];
[proxy purchaseBookWithTitle:@"swift 进阶"];
[proxy purchaseClothesWithColor:@"彩虹色"];*/
Person *p = [[Person alloc] init];
Student *s = [[Student alloc] init];
WJProxy *proxy = [WJProxy alloc];
[proxy transformToObject:p];
Person *person = (Person *)proxy.object;
[proxy performSelector:@selector(setName:) withObject:@"小米"];
person.name = @"小李";
NSLog(@"%@",person.name);
[proxy performSelector:@selector(eat)];
[proxy transformToObject:s];
[proxy performSelector:@selector(study)];
}
我们可以看到这种方式写出来的不仅能调用类方法还能直接使用属性,感觉比之前的方法更为强大。
网友评论