@protocol ContactCtrlDelegate -(void)DismissContactsCtrl; @end @interface ContactsCtrl : UIViewController { id <ContactCtrlDelegate> delegate; } @property (nonatomic, assign) id <ContactCtrlDelegate> delegate;.m
@synthesize delegate;
好比:UITextView
html
@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; @end二、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]; }
三、ProtocolDemoCtrl.h
ui
#import <UIKit/UIKit.h> #import "ContactsCtrl.h" @interface ProtocolDemoCtrl : UIViewController <ContactCtrlDelegate>{//加入托付 ContactsCtrl *contactsView; }
四、ProtocolDemoCtrl.m
atom
#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方法spa
[delegate DismissContactsCtrl];类B实现了这个协议,在.h文件里定义类A的对象a,在.m文件里需要实现methodA方法。并且需要设置托付
a.delegate = self;//设置托付
假设MethodA返回的是B类的对象,那么在A类中就可以调用B类属性和方法国,B这个类能够调用A的属性和方法。code
版权声明:本文博客原创文章。博客,未经赞成,不得转载。orm