iPhone应用中Protocol协议使用方法是本文要介绍的内容,文章有很详细的介绍了Protocol协议的使用方法,一起来看详细内容。
一、说明
两个类进行通讯,用协议就比较方便。
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)textViewShouldBeginEditing:(UITextView *)textView;
- - (BOOL)textViewShouldEndEditing:(UITextView *)textView;
- - (void)textViewDidBeginEditing:(UITextView *)textView;
- - (void)textViewDidEndEditing:(UITextView *)textView;
- - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text;
- - (void)textViewDidChange:(UITextView *)textView;
- - (void)textViewDidChangeSelection:(UITextView *)textView;
- @end
如果要调用以上这些方法,就必须设置UITextView的委托:TextView.delegate = self;