2010-06-14 36 views
0

我有一個在我的RootViewController中初始化的數組和一個將Objects添加到數組的方法。我在我的SecondViewController中創建了一個RootViewController對象。該方法運行(輸出消息),但不會向數組添加任何內容,並且該數組似乎爲空。代碼如下,有什麼建議?RootViewController中的方法不存儲數組

RootViewController.h

#import "RootViewController.h" 
#import "SecondViewController.h" 

@implementation RootViewController 
- (void)viewDidLoad { 
    [super viewDidLoad]; 
    myArray2 = [[NSMutableArray alloc] init]; 

    NSLog(@"View was loaded"); 
} 
-(void)addToArray2{ 
    NSLog(@"Array triggered from SecondViewController"); 
    [myArray2 addObject:@"Test"]; 
    [self showArray2]; 
} 

-(void)showArray2{ 
    NSLog(@"Array Count: %d", [myArray2 count]); 
} 
-(IBAction)switchViews{ 
    SecondViewController *screen = [[SecondViewController alloc] initWithNibName:nil bundle:nil]; 
    screen.modalTransitionStyle = UIModalTransitionStyleCoverVertical; 
    [self presentModalViewController:screen animated:YES]; 
    [screen release]; 
} 

SecondViewController.m

#import "SecondViewController.h" 
#import "RootViewController.h" 

@implementation SecondViewController 

-(IBAction)addToArray{ 

    RootViewController *object = [[RootViewController alloc] init]; 
    [object addToArray2]; 

} 
-(IBAction)switchBack{ 
    [self dismissModalViewControllerAnimated:YES]; 
} 

編輯*************

與馬特的代碼,我有以下錯誤:

「在'RootViewController'之前預期的限定符 - 限定符列表'」

回答

0

您錯過了一些非常重要的基礎知識。如果您在您的SecondViewController中分配了一個新的RootViewController,它與您用於創建SecondViewController的實例不同,因此它不會引用您要添加對象的數組。你試圖做的事情不會奏效。您必須在您的RootViewController的SecondViewController中創建一個ivar,然後在第二個視圖中訪問它。事情是這樣的:

-(IBAction)switchViews{ 
    SecondViewController *screen = [[SecondViewController alloc] 
             initWithNibName:nil bundle:nil]; 
    screen.modalTransitionStyle = UIModalTransitionStyleCoverVertical; 
    [screen setRootViewController:self]; 
    [self presentModalViewController:screen animated:YES]; 
    [screen release]; 
} 

你會伊娃宣佈需要這樣的SecondViewController.h:

@property (nonatomic, retain) RootViewController *rootViewController; 

然後在.M合成

然後,您可以訪問伊娃在您的SecondViewController中:

-(IBAction)addToArray{ 
    [[self rootViewController] addToArray2]; 
} 
+0

讓我問你。 [屏幕setRootViewController:self]做什麼?根據我的想法,當SecondViewController nib加載時,這行代碼幾乎使RootViewController成爲本地控制器? – Tony 2010-06-15 19:10:11

+0

它只是給你的SecondViewController一個對RootViewController的引用,以便它可以訪問它並調用它創建的-addToArray2方法。我不確定你的* native * controller是什麼意思。 – 2010-06-15 19:59:44

+0

沒關係,你清除我的困惑:)我會試試這個。謝謝你的解釋。 – Tony 2010-06-16 01:46:13

相關問題