协议是通过网络,计算机使用者进行通讯后,互相进行约定规定的集合。
这样完成了整个协议传值的方法。
协议分为正式协议和非正式协议,写法上的区别是:非正式协议用@interface 来定义
;正式协议用@protocol来定义。
其实就是非正式协议(interface)换了一种写法而已,看上去更正规一些,语义上更强烈一些:要求采用该协议的类,”必须”实现协议中约定的方法。但是即使号称正式协议,编译器在编译时,遇到不守规矩的情况,仍然只是给出警告。
协议的作用是:
正式协议可以将业务中的方法定义分出来,形成一个单独的文件。如果两个系统需要交换数据,可以指定一套双方都遵守的协议,然后在这两个系统中都把这个协议文件添加到项目中,实现它的必须实现方法即可。这一功能,非正式协议(@interface)就做不到了。
协议不是类,它是定义了一个其他对象可以实现的接口。如果在某一个类中实现了协议中的方法,也就是这个类实现了那个协议。协议中:@optional 下的协议方法是可以选择实现的,@required 下的协议方法是必须实现的。系统SDK中默认的是@required,带有@optional 字样的就表示可以选择实现
协议只声名方法,接受协议的对象负责实现方法。
协议本身可以接收其他协议
那么我们什么时候使用协议呢,通常在往回传值时运用协议,
下面是协议的使用:举一个老板让秘史制订协议给员工的例子
//秘书类定义协议
#import <Foundation/Foundation.h>
#import “SecondProtocal.h"
@protocol SecretoryProtocol <NSObject,SecondProtocal]]>//SecretoryProtocol为协议名字,中间仅仅声名方法
@required//必须实现(可不写,系统默认)
-(void)drink;
@optional//非必须实现,选择性实现
-(void)eat;
@end
//老板类针对这份协议要设置个代理人,
#import <UIKit/UIKit.h>
#import "SecretoryProtocol.h"
@interface BossView : UIView
@property (nonatomic,assign)id<SecretoryProtocol> delegate;//代理人
@end
//老板类.m里要求点击按钮,员工类就要执行协议的方法
#import "BossView.h"
@implementation BossView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setFrame:CGRectMake(0, 0, 72, 37)];
[button setTitle:@"走着" forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:button];
[button release];
}
return self;
}
-(void)buttonAction:(id)sender{
NSLog(@"button=====");
[self.delegate drink];//按钮执行行为
@end
//员工就是代理人,所以员工要遵循这个协议
#import <UIKit/UIKit.h>
#import "SecretoryProtocol.h"
@interface RootViewController : UIViewController
<SecretoryProtocol]]>//遵循这个协议
@end
//.m中实现
#import "RootViewController.h"
#import "BossView.h"
@interface RootViewController ()
@end
@implementation RootViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
BossView *boss = [[BossView alloc]initWithFrame:CGRectMake(0, 50, 100, 100)];
[boss setBackgroundColor:[UIColor brownColor]];
boss.delegate = self;
[self.view addSubview:boss];
[boss release];
}
#pragma mark -
#pragma mark secretary protocal
-(void)drink{
NSLog(@"%s",__func__);
}
-(void)eat{
NSLog(@"%s",__func__);
}
-(void)drive{
NSLog(@"%s",__func__);
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
这样完成了整个协议传值的方法。