使用delegate實現回調Callback
一個ViewController(vc1)中使用了另一個ViewController(vc2),假如vc2中有個按鈕,按下這個按鈕,
vc1中需要知道vc2中的那個按鈕是否被按下時,vc2如何來通知vc1他的按鈕被按下了。
這時候,使用delegate實現回調Callback,通知狀態是一個非常好的方法。
/***************************
ViewController2
***************************/
// *** ViewController2.h ***
id delegate;
}
@property (assign) id delegate;
@end
@protocol ViewController2Delegate
- (void)isButtonPressed:(BOOL)pressed;
@end
// *** ViewController2.m ***
@implement ViewController2
@synchronize delegate;
- (void)viewDidLoad {
[super viewDidLoad];
}
-(void)viewDidUnload {
delegate = nil;
[super viewDidUnload];
}
-(void)test {
// 需要給ViewController1通知狀態時候,調用以下代碼
if ([delegate respondsToSelector:@selector(isButtonPressed:)]) {
[delegate isButtonPressed:YES];
}
}
@end
/***************************
ViewController1
***************************/
#import "ViewController2.h"
@interface ViewController1 : ViewController <ViewController2Delegate> {
}
@end
@implement ViewController1
- (void)viewDidLoad {
[super viewDidLoad];
ViewController2 *vc2 = [[[ViewController2 alloc] init] autorelease];
vc2.delegate = self;
vc2.view.frame = CGRectMake(0, 0, 320, 200);
[self.view addSubview:vc2.view];
}
#pragma mark-
#pragma mark ViewController2Delegate Protocol
#pragma mark --
- (void)isButtonPressed:(BOOL)pressed {
//ViewController2的動作一旦動作,通知ViewController1,觸發次函數
//此處可添加觸發後的處理
}
@end