2010-07-30 21 views
1

我有一個UIViewController,它有一個UIPopoverController,它有一個UINavigationController,然後是一個UIViewController。我如何從子UIViewController調用父UIViewController中的方法(例如。 - (void)update)?嘗試了很多組合,但仍然沒有奏效。嵌套父控制器中的調用方法

回答

5

在你的孩子:

@interface MyChildController:UIViewController { 
    MyParentController *parent; 
} 
@property(nonatomic, assign) MyParentController *parent; 
@end 
@implementation MyChildController 
@synthesize parent; 
... 

在你父控制器,實例化你的孩子時:

MyChildController *newChild = [[[MyChildController alloc] initWithNibName:nil bundle:nil] autorelease]; 

newChild.parent = self; 

... 

現在你的孩子,你有裁判你的父母,你可以使用。例如,你孩子的某種方法:

- (IBAction)someAction { 
    [self.parent doSomethingParentsDo]; 
} 
+0

謝謝!我知道「關注點分離」有一些問題,但我確實需要訪問父視圖控制器上的函數。搜索網站的高低這個簡單的東西,謝謝。 – Rail24 2013-04-03 13:04:06

1

一種可能的方法是使用NSNotificationCenter。在父ViewController的viewDidLoad:方法中,將其註冊爲某個通知的觀察者(在我的示例中,我將使用@「DummyNotification」作爲通知名稱)。然後將該通知從適當的方法發佈到子ViewController中。其結果將是這個樣子:

ParentViewController.m

- (void) viewDidLoad 
{ 
    /* existing code */ 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(update) name:@"DummyNotification" object:nil]; 
} 

- (void) update 
{ 
    //method body 
} 

ChildViewController.m

//put this line wherever you want the ParentViewController to call -update 
[[NSNotificationCenter defaultCenter] postNotificationName:@"DummyNotification" object:self]; 

參考:NSNotificationCenter Class Reference

而且,這個問題被標記爲iPhone,但蘋果UIPopoverController文檔指出,該類專門用於iPad,並且不適用於其他設備。這個問題被標記爲錯誤嗎?

參考:UIPopoverController Class Reference