代理原理(自己的见解,下面的看不懂的读一读这三句话,再看)
拿到代理自己的类的引用,
并让它实现自己要调用的方法,
通过这个类的引用去调用被它实现的方法(编译器自己执行方法选择器)
代理声明格式
@protocol TestDelegate <NSObject>
-(void) logStr:(NSString *) str;
@end
使用代理
@interface XMRotationChartView : UIView
@property (nonatomic, assign) id <XMRotationChartViewDelegate> delegate;
@end
@implementation XMRotationChartView
-(void) test{
[self.delegate logStr:@"Hello"];
}
使用代理方法的例子
[self addObserver:self forKeyPath:@"delegate" options:NSKeyValueObservingOptionNew context:nil];
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
if ([@"delegate"isEqualToString:keyPath]) {
if (_delegate != nil) {
NSlog(@"代理成功");
[self.delegate logStr:@"Hello"];
}else{
NSlog(@"代理被取消了");
}
}
}