代理的另一種實現方式

作者: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]即可。

第二種實現方式適合會有很多個有共同基類的類需要實現同一代理的情況。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章