@protocol ContactCtrlDelegate -(void)DismissContactsCtrl; @end @interface ContactsCtrl : UIViewController { id.mdelegate; } @property (nonatomic, assign) id delegate;
@synthesize delegate;
例如:UITextView
@protocol UITextViewDelegate如果要調用以上這些方法,就必須設置UITextView的委托:TextView.delegate = self;@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
四、Demo
#import2、ContactsCtrl.m//定義協議 @protocol ContactCtrlDelegate -(void)DismissContactsCtrl; @end @interface ContactsCtrl : UIViewController { IBOutlet UINavigationBar *ContactNavBar; id delegate; } @property (nonatomic, assign) id delegate; -(IBAction)canCelBtn:(id)sender; @end
@implementation ContactsCtrl @synthesize delegate; // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. - (void)viewDidLoad { [super viewDidLoad]; ContactNavBar.topItem.prompt = @選取聯系人發送短信; } //調用協議中的方法 -(IBAction)canCelBtn:(id)sender{ [delegate DismissContactsCtrl]; }
3、ProtocolDemoCtrl.h
#import#import ContactsCtrl.h @interface ProtocolDemoCtrl : UIViewController {//添加委托 ContactsCtrl *contactsView; }
4、ProtocolDemoCtrl.m
#import ProtocolDemoCtrl.h #define BARBUTTONADD(SELECTOR) [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:SELECTOR] autorelease]; @implementation ProtocolDemoCtrl @synthesize contactsView; // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. - (void)viewDidLoad { [super viewDidLoad]; self.navigationItem.rightBarButtonItem = BARBUTTONADD(@selector(addContactAction:)); } - (void)addContactAction:(id)sender{ ContactsCtrl *contactView = [[ContactsCtrl alloc] initWithNibName:@ContactsCtrl bundle:nil]; self.contactsView = contactView; contactsView.delegate = self;//設置委托 [self presentModalViewController:contactsView animated:YES]; [contactView release]; } //實現ContactCtrlDelegate協議中的方法 -(void)DismissContactsCtrl{ [contactsView dismissModalViewControllerAnimated:YES]; }
綜上,如果A類.h文件定義了一個協議,在A類裡面我們還需要定義一個委托delegate,協議裡面有個必須實現的methodA方法(@required,這個方法在實現了協議的類裡面實現),在A類的.m文件中需要調用這個methodA方法,我們使用委托調用這個methodA方法
[delegate DismissContactsCtrl];類B實現了這個協議,在.h文件中定義類A的對象a,在.m文件中需要實現methodA方法,並且需要設置委托
a.delegate = self;//設置委托
如果MethodA返回的是B類的對象,那麼在A類中就可以調用B類屬性和方法,B類中也可以調用A的屬性和方法了。