作者:Love@YR
链接:http://blog.csdn.net/jingqiu880905/article/details/52461820
请尊重原创,谢谢!
代理相信大家都很熟悉了。不过还是说下吧。
举个例子:
//
// A.h
// Created by XX
//
@protocol SomeDelegate <NSObject>
- (void)someMethod:(UIViewController *)vc;
//and other methods....
@end
@interface A:NSObject
@property (nonatomic,weak) id <SomeDelegate> sdelegate;
@end
//
// A.m
// Created by XX
//
#import "A.h"
@implementation A
-(void)Method2{
if (self.sdelegate && [self.sdelegate respondsToSelector:@selector(someMethod:)]) {
[self.sdelegate someMethod:someParam];//如果someMethod没引用 可以用performSelector
}
}
@end
//
// B.h
// Created by XX
//
@interface B:UIViewController<SomeDelegate>
@end
//
// B.m
// Created by XX
//
@implementation B
-(void)Method1{
A *a =[[A alloc]init];
a.sdelegate = self;
}
#pragma mark -SomeDelegate
- (void)someMethod:(UIViewController *)vc{
//do something.....
}
@end
现在我在A中加入一个方法newAwithController
+ (instancetype)newAwithController:(UIViewController *)controller{
A *a = [[self alloc]init];
if ([controller conformsToProtocol: @protocol(SomeDelegate)]) {
a.sdelegate = (UIViewController<SomeDelegate> *)controller;
}
return a;
}
这样的话所有需要实现协议的类里如B类都不必再写Method方法里那两句了。而是在newA的时候,直接self.a=[A newAwithController:self]即可。
第二种实现方式适合会有很多个有共同基类的类需要实现同一代理的情况。