簡(jiǎn)介:通過(guò)NSProxy 可以實(shí)現(xiàn)類的"偽多繼承",demo中KLProxy通過(guò)攔截方法修改了cat和dog本來(lái)的log

Log.png
1.VC實(shí)現(xiàn)
import "ViewController.h"
#import "KLProxy.h"
#import "Dog.h"
#import "Cat.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
Dog * dog = [Dog new];
Cat * cat = [Cat new];
KLProxy * proxy = [KLProxy alloc];
[proxy transform:cat];
[proxy performSelector:@selector(eat:) withObject:nil];
}
@end
2.cat.m 類
#import "Cat.h"
@implementation Cat
-(void)eat:(NSString*)str{
NSLog(@"貓吃~~~貓吃%@",str);
}
@end
3.Dog.m
#import "Dog.h"
@implementation Dog
-(void)wang:(NSString*)str{
NSLog(@"狗叫~~~狗叫%@",str);
}
@end
proxy.h
@interface KLProxy : NSProxy
-(void)transform:(NSObject*)objc;
@end
proxy.m
#import "KLProxy.h"
@interface KLProxy()
@property(nonatomic,strong)NSObject * objc;
@end
@implementation KLProxy
-(void)transform:(NSObject*)objc{
self.objc = objc;
}
-(void)forwardInvocation:(NSInvocation *)invocation{
if(self.objc){
[invocation setTarget:self.objc];
if([self.objc isKindOfClass:[NSClassFromString(@"Cat") class]]){
NSString *str = @"攔截消息";
[invocation setArgument:&str atIndex:2];
}else{
NSString *str = @"我的小狗狗汪汪叫";
[invocation setArgument:&str atIndex:2];
}
//開(kāi)始調(diào)用方法
[invocation invoke];
}
}
-(NSMethodSignature *)methodSignatureForSelector:(SEL)sel{
NSMethodSignature * signature = nil;
if([self.objc methodSignatureForSelector:sel]){
signature = [self.objc methodSignatureForSelector:sel];
}else{
signature = [super methodSignatureForSelector:sel];
}
return signature;
}
@end
http://www.itdecent.cn/p/923f119333d8
proxy解決NSTimer循環(huán)引用的應(yīng)用
http://www.itdecent.cn/p/fca3bdfca42f