2013-02-11 63 views
2

當我嘗試訪問我的parentViewController中的方法時,我的應用程序崩潰。以下是在故事板iOS訪問parentViewController中的屬性

enter image description here

MainViewController = STLMMainViewController(ParentViewController)

場景1 = STLMTimeDateViewController(ChildViewController)

這裏佈局被用於STLMTimeDateViewController

代碼
#import "STLMTimeDateViewController.h" 
#import "STLMMainViewController.h" 

@interface STLMTimeDateViewController() 
@property (nonatomic, strong) STLMMainViewController *stlmMainViewController; 
@end 


- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    NSLog(@"The name of the controller %@",self.navigationController.parentViewController); 

    stlmMainViewController= (STLMMainViewController *) self.parentViewController; 
    [stlmMainViewController locationButtonSelected]; // This is where the App crashes 
    NSLog(@"TimeDateController"); 
} 

該應用運行,但是當調用STLMMainViewController時,該應用程序並出現以下錯誤崩潰:

2013-02-10 16:33:57.422 MyApp[9120:c07] The name of the controller <STLMMainViewController: 0x83850d0> 
2013-02-10 16:33:57.434 MyApp[9120:c07] -[UINavigationController locationButtonSelected]: unrecognized selector sent to instance 0x8371a70 

如果我刪除以下行:

stlmMainViewController = (STLMMainViewController *) self.parentViewController; 

和剛剛離開

[stlmMainViewController locationButtonSelected]; 

應用程序運行,沒有錯誤,但在下面的方法[ STLMMainViewController locationButtonSelected]沒有被調用(我從來沒有看到日誌):

-(void)locationButtonSelected 
{ 
    [LocationButton setSelected:YES]; 
    [eatDrinkbutton setSelected:NO]; 
    [timeCalButton setSelected:NO]; 
    [carButton setSelected:NO]; 
    [contactButton setSelected:NO]; 
    NSLog(@"LocationButtonSelected Method"); 
} 

locationButtonSelected方法和方法本身中的所有屬性都在STLMMainViewController的.h中聲明以供公共訪問。

感謝

+1

類參考蘋果開發者網站說,這對parentViewController ... 如果收件人是一個容器視圖控制器的一個孩子,這個屬性保存它包含在視圖控制器。如果收件人沒有父,該屬性中的值爲零。 在iOS 5.0之前,如果視圖沒有父視圖控制器並且正在呈現,則會返回呈現視圖控制器。在iOS 5上,此行爲不再發生。相反,使用presentsViewController屬性來訪問呈現視圖控制器。 也許試試呈現ViewController – chuthan20 2013-02-11 01:13:19

回答

3

你可以試試這個:

self.stlmMainViewController= (STLMMainViewController *)self.navigationController.parentViewController; 

(編輯:實際上,由於剛纔有人指出,你可能想使用presentingViewController代替)

它看起來像你在此之前,在日誌消息中正確使用了它。在這種情況下,您需要您的導航控制器的父項。

順便說一句,你不會崩潰,當你刪除這條線的原因,是因爲你最終發送locationButtonSelected爲零。這不會崩潰,但它也不會做任何事情。爲的UIViewController

+0

精美的工作!感謝您的代碼和解釋@Firoze Bhai。 – user1107173 2013-02-11 01:14:54

+0

我很高興它解決了。 – 2013-02-11 01:15:31