之前一直困惑delegate的設計模式,自己閒的時候寫了個demo,加了點註釋,希望初學者可以看看,不妥之處請大家指出。
這裏只粘貼出關鍵代碼:
一、 自定義協議:
// xyzDelegate.h
#import <Foundation/Foundation.h>
@protocol xyzDelegate <NSObject>
-(void)showName:(NSString *)name;
@end
//
二、通用寫法都寫爲delegate並給它加nonatomic,assign防止魔鬼引用
B.h
#import <UIKit/UIKit.h>
#import "xyzDelegate.h"
@interface ViewControllerB :UIViewController
{
id<xyzDelegate>delegate;
}
@property(nonatomic,assign)id<xyzDelegate>delegate;
@end
-(void)transvalue{
//上個頁面跳過來的時候設置了指針委託,那麼這裏就會識別到delegate響應了這個方法;
if ([delegate respondsToSelector:@selector(showName:)])
{
UITextField *mytext = (UITextField *)[self.viewviewWithTag:1001];
//step01
[delegateshowName:mytext.text];
[self.navigationControllerpopToRootViewControllerAnimated:YES];
}
}
//調到下個頁面,此時設置下個頁的delegate方法給ViewController本身,這個協議及自定義的協議,協議的是由B來配置的,那麼B裏面可以檢測到其是否將自己的delegate委託給某人,這裏是委託給ViewController,讓它來完成本來應該讓B自己來做的事情,現在由A代勞;
-(void)jp2next
{
ViewControllerB *bvc = [[ViewControllerBalloc] init];
//設置委託
bvc.delegate =self;
[self.navigationControllerpushViewController:bvc animated:YES];
[bvc release];
}
//delegate's method
//step02
//這樣viewController和viewcontrollerB就產生了通信
//這裏的name及由viewControllerb中傳過來的
-(void)showName:(NSString *)name
{
NSLog(@"將b的delegate指定給a,讓a來實現");
lbe.text = [NSStringstringWithFormat:@"%@",name];
NSLog(@"%@",name);
}