iPhone应用中Protocol协议使用方法

iPhone应用中Protocol协议使用方法是本文要介绍的内容,文章有很详细的介绍了Protocol协议的使用方法,一起来看详细内容。

一、说明

两个类进行通讯,用协议就比较方便。

1、协议声明了可以被任何类实现的方法

2、协议不是类,它是定义了一个其他对象可以实现的接口

3、如果在某个类中实现了协议中的某个方法,也就是这个类实现了那个协议。

4、协议经常用来实现委托对象。一个委托对象是一种用来协同或者代表其他对象的特殊对象。

5、委托,就是调用自己定义方法,别的类来实现。

6、新特性说明

@optional预编译指令:表示可以选择实现的方法

@required预编译指令:表示必须强制实现的方法

二、定义

  1. .h  
  2. @protocol ContactCtrlDelegate  
  3. -(void)DismissContactsCtrl;  
  4. @end  
  5.  
  6. @interface ContactsCtrl : UIViewController {  
  7.     id <ContactCtrlDelegate> delegate;  
  8. }  
  9. @property (nonatomic, assign) id <ContactCtrlDelegate> delegate;  
  10. .m  
  11. @synthesize delegate; 

三、例子

例如:UITextView

  1. @protocol UITextViewDelegate <NSObject> 
  2.  
  3. @optional  
  4.  
  5. - (BOOL)textViewShouldBeginEditing:(UITextView *)textView;  
  6. - (BOOL)textViewShouldEndEditing:(UITextView *)textView;  
  7.  
  8. - (void)textViewDidBeginEditing:(UITextView *)textView;  
  9. - (void)textViewDidEndEditing:(UITextView *)textView;  
  10.  
  11. - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text;  
  12. - (void)textViewDidChange:(UITextView *)textView;  
  13. - (void)textViewDidChangeSelection:(UITextView *)textView;  
  14. @end 

如果要调用以上这些方法,就必须设置UITextView的委托:TextView.delegate = self;

posted @ 2012-09-04 23:17  careerman  阅读(286)  评论(0编辑  收藏  举报