2011-07-27 98 views
3

我有兩個視圖控制器。我第一次,當我按下按鈕時,第二個視圖控制器被推到導航控制器堆棧上。在這裏,在第二個視圖控制器中我有一個表格視圖,當我點擊一些行時,它們被選中(如複選框),並將與該行相關的一些數據添加到數組中。現在,當我選擇完成後,我想回到第一個視圖控制器並使用該數組。怎麼做?現在我的應用程序就像這樣工作:我有一個委託協議,然後是具有屬性數組的對象,並且可以從整個應用程序訪問該對象及其數組,然而我不太喜歡這樣。這是正確/最好/最簡單的方法來做到這一點?從彈出視圖控制器傳遞數據

回答

6

我有一個委託協議,然後我有屬性數組的對象,我可以從整個應用程序訪問該對象和它的數組... ...但我不真的那樣。這是正確/最好/最簡單的方法來做到這一點?

委託是在這裏使用的正確模式,但是您描述的並不是委派,而是使用全局變量。也許你在你的App Delegate中存儲全局變量 - 如果可以的話,通常可以避免使用全局變量。

這裏的代碼應該是什麼樣一個大致的輪廓:

SecondViewController.h:

@protocol SecondViewControllerDelegate; 

@interface SecondViewController; 

SecondViewController : UIViewController 
{ 
    id<SecondViewControllerDelegate> delegate; 

    NSArray* someArray; 
} 

@property (nonatomic, assign) id<SecondViewControllerDelegate> delegate; 
@property (nonatomic, retain) NSArray* someArray; 

@end 

@protocol SecondViewControllerDelegate 
- (void)secondViewControllerDidFinish:(SecondViewController*)secondViewController; 
@end 

SecondViewController.m:

@implementation SecondViewController 

@synthesize delegate; 
@synthesize someArray; 

- (void)dealloc 
{ 
    [someArray release]; 
    [super dealloc]; 
} 

- (void)someMethodCalledWhenUserIsDone 
{ 
    [delegate secondViewControllerDidFinish:self]; 
} 

FirstViewController.h:

#import SecondViewController 

@interface FirstViewController : UIViewController <SecondViewControllerDelegate> 
{ 
    ... 
} 

@end 

FirstViewController.m:

@implementation FirstViewController 

- (void)secondViewControllerDidFinish:(SecondViewController*)secondViewController 
{ 
    NSArray* someArray = secondViewController.someArray 
    // Do something with the array 
} 

@end 
+0

謝謝...但也許我做錯了什麼,因爲它不工作:( – Michael

+2

我必須設置secondViewController.delegate =自我;之前我推它...現在它工作:)再次感謝 – Michael

0

您需要reference您的secondViewController,併爲它創建一個對象。

secondViewController *object2 = [[SecondViewController alloc] init]; 

object2.thatArray將具有該數組的內容。確保陣列在離開視圖控制器時保留它的值(或者您可以在您的AppDelegate中創建該陣列,以便它可以被所有viewController訪問)。

相關問題