選項A
這是更快,更容易,但缺乏維護,因爲沒有合同,說明SecondaryViewController需要不厭其煩調用任何東西,self.parentViewController可以是任何的UIViewController。
選項B
委託模式;這是我的偏好,很明顯發生了什麼,需要什麼,還有一個很好的合同,說明如果你想初始化我,給我一個委託。
選項C
如果SecondaryViewController已通知多個對象,這將是快速使用NSNotificationCenter,但與選項A,沒有合同,如果你需要通知很多對象,你需要記住監聽對這些對象的通知 - 因爲這不是問題,我就不細講,只是這裏的信息
選項A
在MainViewController.m,做一些像這樣:
SecondaryViewController *viewcontroller = [[SecondaryViewController alloc] initWithNibName:@"SecondaryView" bundle:nil];
[self addChildViewController:viewcontroller];
//set viewcontroller.view frame
[self.view addSubview:viewcontroller.view];
[viewcontroller didMoveToParentViewController:self];
內部MainViewController.h
-(void) performButtonClickAction;
內部MainViewController.m:
-(void) performButtonClickAction {
//Do something constructive
}
然後SecondaryViewController.m內:
-(IBAction) buttonPressed:(id) sender {
[self.parentViewController performButtonClickAction];
}
選項B
內部SecondaryViewController.h
@protocol SecondaryViewControllerDelegate <NSObject>
-(void) eventAFromViewController:(UIViewController *) viewController;
-(void) eventBFromViewController:(UIViewController *) viewController;
@end
@interface SecondaryViewController : UIViewController {
id<SecondaryViewControllerDelegate> delegate;
}
@property (assign, nonatomic) id<SecondaryViewControllerDelegate> delegate;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil delegate:(id<SecondaryViewControllerDelegate>) theDelegate;
@end
內部SecondaryViewController.m @synthesize代表= _delegate;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil delegate:(id<SecondaryViewControllerDelegate>) theDelegate
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.delegate = theDelegate;
}
return self;
}
-(IBAction) buttonPressed:(id) sender {
if(self.delegate != nil) {
[_delegate eventAFromViewController:self];
}
else {
//No delegate
}
}
。謝謝 –
它的作品的主題使用選項B中得到回報 –