2012-02-27 83 views
0

我只是想知道這是否是在iphone/ipad中的不同視圖之間傳遞數據或消息的正確方式。dismissModalViewController在消息在視圖控制器之間傳遞

我有兩個ViewControllers,FirstViewController和SecondViewController。我有一個NSString *消息作爲我的ViewControllers中的一個屬性,我通過以下方式進行設置。

在FirstViewController.h中,我導入了SecondViewController.h類。我有這個IBAction爲被調用,當用戶點擊第一視圖中的按鈕

-(IBAction)ShowSecondView 
{ 

    SeondViewController *secondView = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:[NSBundle mainBundle]]; 

    secondView.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal; 
    secondView.message = @"Presented from First View"; 

    [self presentModalViewController:secondView animated:YES]; 

    [secondView release]; 

} 

在我SecondViewController.h,我導入類FirstViewController.h 我有這個IBAction爲被調用,當用戶點擊一個按鈕第二視圖

-(IBAction)GoBack 
{ 

    FirstViewController *firstView = [[FirstViewController alloc] initWithNibName:@"FirstViewController" bundle:[NSBundle mainBundle]]; 

    firstView.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal; 
    firstView.message = @"Presented from Second View"; 

    [self presentModalViewController:firstView animated:YES]; 

    [firstView release]; 

} 

的消息被成功地在視圖之間通過,但如果使用以關閉當前視圖控制器返回到在父視圖 [self dismissModalViewController],不傳遞該消息。

+0

我的建議是使用委託 – Bonny 2012-02-27 09:53:11

回答

0

在GoBack的你的firstView alloc'd不是提出的第二個視圖控制器的第一個視圖控制器。這是FirstViewController類的新實例。而不是創建這個firstView實例,你只需要關閉第二個視圖控制器。但是,您還需要在第二個視圖控制器中創建一個指向第一個視圖控制器的指針,以便您可以在其中設置數據。

在第二視圖控制器的報頭

@synthesize firstView; 
在第一視圖控制器

-(IBAction)ShowSecondView { 
    SeondViewController *secondView = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:[NSBundle mainBundle]]; 
    secondView.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal; 
    secondView.message = @"Presented from First View"; 
    secondView.firstView = self; 
    [self presentModalViewController:secondView animated:YES]; 
    [secondView release]; 
} 

#import "FirstViewController.h" 
FirstViewController *firstView; 
@property (retain, nonatomic) firstViewController *firstView; 
在第二視圖控制器的實施

你的第二個視圖控制器:

-(IBAction)GoBack { 
    firstView.message = @"Presented from Second View"; 
    [self dismissModalViewControllerAnimated:YES]; 
} 

順便說一句,還有其他的方式viewcontrollers之間的溝通,我經常使用Notifications

順便說一句,上面的代碼是未經測試的直離開我的頭。如果有任何問題,我們表示歉意。

+0

這將導致「循環導入」問題。任何方式我會使用通知或代表。謝謝你的時間。 – 2012-02-29 11:17:09

+0

它不會導致「循環導入」問題。在這種方法中,第一個ViewController導入第二個,但第二個不導入第一個(它會自動返回到原來的第一個)。 – ader 2012-02-29 11:26:02

相關問題