@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;
#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; @end2、ContactsCtrl.m
@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 <UIKit/UIKit.h> #import "ContactsCtrl.h" @interface ProtocolDemoCtrl : UIViewController <ContactCtrlDelegate>{//添加委托 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的属性和方法了。
IOS开发之——Protocol协议的使用,布布扣,bubuko.com
原文地址:http://blog.csdn.net/zhenyu5211314/article/details/25301157