借鉴了网络资料,总结了下协议的做用以及用法。网络
一、协议是一组通信协议,通常用做两个类之间的通讯。ui
二、协议声明了一组全部类对象均可以实现的接口。atom
三、协议不是类,用@protocol关键字声明一个协议。spa
四、与协议有关的两个对象,代理者和委托者。.net
五、代理,实现协议的某个方法,至关于实现这个协议。代理
六、委托,用本身的方法,指定要实现协议方法的对象(代理),代理来实现对应的方法。对象
其中,两个预编译指令,@optional:表示能够选择实现的方法。接口
@required:表示强制执行的方法。字符串
贴一个小例子。get
协议:SetStringDelegate
#import <Foundation/Foundation.h>
@protocol SetStringDelegate <NSObject>
- (NSString *)getString;
委托类
RootViewController.h
#import <UIKit/UIKit.h>
#import "SetStringDelegate.h"
@interface RootViewController : UITabBarController
@property (nonatomic)id<SetStringDelegate>delegate;
RootViewController.m
- (void)secondView
{
SecondViewController * second = [[SecondViewController alloc] init];
[self.navigationController pushViewController:second animated:YES];
[second release];
}
- (void)viewDidLoad
{
[superviewDidLoad];
UIBarButtonItem * rightItem = [[UIBarButtonItem alloc] initWithTitle:@"next"style:UIBarButtonItemStyleDone target:self action:@selector(secondView)];
self.navigationItem.rightBarButtonItem = rightItem;
[rightItem release];
SecondViewController * second = [[SecondViewController alloc] init];
self.delegate = second;//指定代理对象为,second
NSString * str = [self.delegate getString];//这里得到代理方法的返回值。
[second release];
}
代理类
SecondViewController.h
#import <UIKit/UIKit.h>
#import "SetStringDelegate.h"
@interface SecondViewController : UITabBarController<SetStringDelegate>
并在SecondViewController.m中实现代理方法
- (NSString *)getString
{
return @"test";//返回一个test字符串。
}
一个简单的代理回调
也能够把代理对象设置为自身,能够在自身中实现协议方法。
这简单的两个类传值,能够用或不用代理,复杂的项目中,好比第三个类要获得协议方法的返回值。
用代理会比较方便。
其中项目中用到一个组合的概念,至今不太明白,代码先贴出来
#import <Foundation/Foundation.h>
#pragma mark -
#pragma mark delegate
//一个协议方法
@protocol MSCNodeAttributeSetterDelegate <NSObject]]>
- (void) reloadWithAttribute_Style;
#pragma mark -
#pragma mark class
//提供一组接口,可是,又不是协议
@protocol MSCNodeAttributeSetter
@property (nonatomic, assign) id<MSCNodeAttributeSetterDelegate> AttributeSetDelegate;
//在这,只要引入这个接口,能够做为一个委托。其中引入接口也用<MSCNodeAttributeSetter>
- (void) setAttribute_Style:(NSString *)style;
//在委托设置代理类