讯,用协议就比较方便。下面是 CocoaChina 版主“angellixf”为新手写的协议入门介绍
以及代码例子,希望对刚入门开发者有所帮助
一、说明
1.协议声明了可以被任何类实现的方法
2.协议不是类,它是定义了一个其他对象可以实现的接口
3.如果在某个类中实现了协议中的某个方法,也就是这个类实现了那个协议。
4.协议经常用来实现委托对象。一个委托对象是一种用来协同或者代表其他对象的特殊对
象。
5:委托,就是调用自己定义方法,别的类来实现。
6.新特性说明
@optional 预编译指令:表示可以选择实现的方法
@required 预编译指令:表示必须强制实现的方法
二、定义
.h
@protocol ContactCtrlDelegate
-(void)DismissContactsCtrl;
@end
@interface ContactsCtrl : UIViewController {
id <ContactCtrlDelegate> delegate;
}
@property (nonatomic, assign) id <ContactCtrlDelegate> delegate;
.m
@synthesize delegate;
三、例子
例如:UITextView
@protocol UITextViewDelegate <NSObject>
@optional
- (BOOL)textViewShouldBeginEditi
- (BOOL)textViewShouldEndEditing
- (void)textViewDidBeginEditing:(UITextView *)textView;
- (void)textViewDidEndEditing:(UITextView *)textView;
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range
replacementText:(NSString *)text;
- (void)textViewDidChange:(UITextView *)textView;
- (void)textViewDidChangeSelecti
@end
如果要调用以上这些方法,就必须设置 UITextView 的委托:TextView.delegate = self;
四、Demo
1、ContactsCtrl.h
#import <UIKit/UIKit.h>
//定义协议
@protocol ContactCtrlDelegate
-(void)DismissContactsCtrl;
@end
@interface ContactsCtrl : UIViewController {
IBOutlet UINavigationBar *ContactNavBar;
id <ContactCtrlDelegate> delegate;
}
@property (nonatomic, assign) id <ContactCtrlDelegate> delegate;
-(IBAction)canCelBtn:(id)sender;
@end
2、ContactsCtrl.m
@implementation ContactsCtrl
@synthesize delegate;
// Implement viewDidLoad to do additional setup after loading the view, typical
ly from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
ContactNavBar.topItem.prompt = @"选取联系人发送短信";
}
//调用协议中的方法
-(IBAction)canCelBtn:(id)sender{
[delegate DismissContactsCtrl];
}
3、ProtocolDemoCtrl.h
#import <UIKit/UIKit.h>
#import "ContactsCtrl.h"
@interface ProtocolDemoCtrl : UIViewController <ContactCtrlDelegate>{//添加委托
ContactsCtrl *contactsView;
}
4、ProtocolDemoCtrl.m
#import "ProtocolDemoCtrl.h"
#define BARBUTTONADD(SELECTOR) [[[UIBarButtonItem alloc] initWithBarButtonSyste
mItem:UIBarButtonSystemItemAdd
@implementation ProtocolDemoCtrl
@synthesize contactsView;
// Implement viewDidLoad to do additional setup after loading the view, typical
ly from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationItem.rightBarButtonItem = BARBUTTONADD(@selector(addContactA
ction:));
}
- (void)addContactAction:(id)sender{
ContactsCtrl *contactView = [[ContactsCtrl alloc] initWithNibName:@"Contact
sCtrl" bundle:nil];
self.contactsView = contactView;
contactsView.delegate = self;//设置委托
[self presentModalViewControll
[contactView release];
}
//实现 ContactCtrlDelegate 协议中的方法
-(void)DismissContactsCtrl{
[contactsView dismissModalViewControll
}
委托代理,顾名思义,把某个对象要做的事情委托给别的对象去做。
读取
id