简单代理 设置

一、理解协议与代理
协议是一个方法签名的列表,在其中可以定义若干个方法。根据配置,遵守该协议的类会去实现这个协议中规定的若干个方法。

代理是一个概念,很难用一个名词去定义(如我们可以说协议其实就是一个方法列表)。它更像是一种关系,我要做某一个事情,但我自己不想去做这件事,我委托其他人帮我去做这件事。这个时候,这位其他人就是我的代理。

二、协议的使用

在定义协议时,可以通过@required与@optional来配置遵守这个协议必须去实现的方法和可以选择的方法。譬如:

@protocol MyRootViewDelegate<NSObject>  

//必须的
@required  

-(void)ChooseDay:(id)choose;

//可选的

@optional  

-(void)hideThisView;

- (void)changeDateFormatter:(NSString*)formatString;  
@end  


在定义的协议 MyRootViewDelegate中,如果遵守该协议,就必须实现协议中的-(void)ChooseDay:(id)choose;方法,同时可以根据实际程序要求去实现 -(void)hideThisView; 与- (void)changeDateFormatter:(NSString*)formatString; 。

同时,协议支持对本身的一种扩展,譬如:

@protocol MyRootViewDelegate< MyChooseDayViewDelegate>  
-(void) doSomething; 
@end  


MyVRootViewDelegate扩展了MyChooseDayViewDelegate这个协议,也就是说,假如遵守了MyRootViewDelegate的话,也必须实现MyChooseDayViewDelegate中的方法(@required)使用分类的话,就是在定义类的头文件中使用<> 将所需要的协议引入,如果引入多个协议,用","分隔,譬如:

@interface MyClassView:UIViewController <MyRootViewDelegate, UIAlertViewDelegate>  
//TODO: balabalabala...  
@end  

在view.h中

#import <UIKit/UIKit.h>

//声明一个代理

@protocol EverySomthing

-(void)doSomthing;

@end

@interface LNView : UIView

@property(nonatomic,retain)NSTimer *timer;

@property(nonatomic,assign)NSInteger inter;

@property(nonatomic,retain)id<EverySomthing>mydelegata;

@end

view.m中

#import "LNView.h"

@implementation LNView

 -(id)initWithFrame:(CGRect)frame

{

    self = [super initWithFrame:frame];

    if (self) { 

        self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(actiiio) userInfo:nil repeats:YES];

        [self.timer fire];

        }

    return self;

}

 -(void)actiiio

{

    [self.mydelegata doSomthing];

}



想要检查某个类是否实现了某个协议或者某个类是否实现了某个协议的方法,可以通过以下方式来进行测试

 //在controller中检测

    ViewController *view=[[ViewController alloc]init];

    //判断该对象是否实现了EverySomthing  协议

    if ([view conformsToProtocol:@protocol (EverySomthing)])

    {

        NSLog(@"我实现了这个协议");

    } 

    //判断该对象是否实现了doSomthing 方法

    if ([view respondsToSelector:@selector(doSomthing)]) {

        NSLog(@"我实现了某个方法"); //  respondsToSelector是继承于NSObject

    }

原文地址:https://www.cnblogs.com/luningning0901/p/4167536.html