2011-07-01 220 views
1

FirstViewController.h訪問變量:從另一個視圖控制器

#import <UIKit/UIKit.h> 

    @interface FirstViewController : UIViewController 
    { 
    NSArray *listData; 
} 
-(IBAction) GoToInsert: (id) sender; 
@property (nonatomic, retain) NSArray *listData; 
@end 

FirstViewController.m:

-(IBAction) upisiRezultat:(id)sender 
{ 
    SecondViewController *secondView = [[SecondViewController alloc] initWithNibName: nil bundle: nil]; 
    [self presentModalViewController: secondView animated: NO]; 
    [secondView release]; 
} 

- (void)viewDidLoad 
{NSArray *array = [[NSArray alloc] initWithObjects:@"236", @"46", 
        @"147", @"8", @"56", @"69", @"114", @"2", 
        @"96", @"518", @"2", @"54", @"236", nil]; 
    self.listData = array; 
    [array release]; 
    [super viewDidLoad]; 
} 

SecondViewontroller.h

@interface SecondViewController : UIViewController { 

} 
-(IBAction) insert; 
@end 

SecondViewontroller.m

-(IBAction) insert 
{ 
    /* Here should be the code to insert some number in listData from FirstViewController */ 
} 

所以,當應用程序加載它加載FirstViewController.xib並在屏幕上顯示的listData陣列,當我點擊按鈕「去插入」另一種觀點被加載(SecondViewController.xib )與「插入」按鈕,它應該添加一些數字到數組中,並在第一個視圖上顯示新的數組。

如何做到這一點?

+0

更具可讀性的代碼: http://pastebin.com/GBk1V7ac – vburojevic

+0

您可以在Stack Overflow上格式化代碼,在單擊'{}'時寫入題。 – ryyst

+0

@Wikiboo:讓我知道如果該代碼有幫助! – Legolas

回答

0

您可以通過self.parentViewController訪問父視圖控制器。因此這些方針的東西(指我沒有測試過這一點 - 你應該)應該工作:

FirstViewController *firstViewController = self.parentViewController; 
NSMutableArray *newArray = [[NSMutableArray alloc] initWithArray:firstViewControl.listData]; 
[newArray addObject:@"42"]; 
[firstViewController setListData:[NSArray arrayWithArray:newArray]]; 
[newArray release]; 

不過,既然你要的對象添加到listArray,它會更自然地用一個NSMutableArray代替。此外,您目前正在向陣列中添加NSString s,當它看起來更像是您想擁有NSNumber對象時。

+0

我應該在AppDelegate.h中有FirstViewController和SecondViewController的實例嗎? – vburojevic

+0

我不知道。我看不到你的AppDelegate.h文件,我不知道你的應用程序是如何組織的。上面的代碼是我爲你在SecondViewController.m中的' - (IBAction)insert'方法提出的。 – PengOne

+0

我會盡力讓你知道它是否有效:) 另一個問題,視圖控制器之間共享變量的最佳方式是什麼? – vburojevic

0

我不知道你是否有imported SecondViewController.h,我想我有一個想法,你正在嘗試做什麼。

+0

是的,這非常有幫助! :) 這是傳遞價值beetwen視圖控制器的常用方式? – vburojevic

+0

是的。它是:) .. – Legolas

0

另外,也許更容易,你可以在你的主AppDelegate中有變量。

把: int myNumber; 在projectname_AppDelegate.h文件

然後在每個視圖控制器,您可以導入AppDelegate.h文件,然後像做:

的AppDelegate *的appDelegate =(AppDelegate中*)[[UIApplication的sharedApplication]代表]; 然後讀取或修改:

appDelegate.myNumber

===

這是不是你應該做的事情所有的時間(你不想讓你的appDelegate是一個巨大的數據存儲庫),但它可以讓你在需要時快速修復...

+0

我應該在其他視圖控制器的每個方法中聲明 AppDelegate * appDelegate =(AppDelegate *)[[UIApplication sharedApplication] delegate]; appDelegate.myNumb 如果我想在這些方法中使用該變量? 我很難搞清楚在視圖控制器之間共享變量的最佳方法是什麼... – vburojevic

+0

在您的FirstViewController.h中,導入應用程序委託並具有變量AppDelegate * appDelegate;然後,在viewdidload中,說appDelegate =(AppDelegate *)[[UIApplication sharedApplication]委託]; ...然後,無論你需要它,只要參考appDelegate.myNumber –

相關問題