2011-05-23 75 views
1

我知道如何處理2個視圖之間的共享數據。但是,如果我想使用tabBarController共享數據,我會迷路。在UITabBarController的UIViewController和UIViewController之間共享數據xcode

這是我的IBAction移動到我的tabBar。

-(IBAction)goToPage2:(id)sender 
{ 
tabController.modalTransitionStyle=UIModalTransitionStyleFlipHorizontal; 
[self presentModalViewController:tabController animated:YES]; 
} 

我需要在我的tabBar的第一個視圖中在我的IBAction中共享我的NSString * dataStr。

firstView *first = [[firstView alloc] initWithNibName:@"firstView" bundle:nil]; 
first.dataStr = name.text; 
[tabController presentModalViewController:first animated:YES]; 

此代碼不起作用。

THX

回答

3

中聲明你的應用程序委託一個@property。你可以從你的應用程序的任何位置訪問你的應用程序委託。

MyAppDelegate *appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication ]delegate] 
+0

這是作品好謝謝! – user627441 2011-05-24 11:17:44

3

我同意Terente的建議。但我建議你在這種情況下應該使用數據類。在Appdelegate中使用屬性不是一個好習慣。你應該總是使用這個數據類。
您可以創建一個Data類,如下所示:
您需要創建一個Data類,您可以在其中設置變量的屬性或您的案例數組(用於在UITableView中顯示數據)。在數據類中實現一個類方法,用於檢查對象是否被實例化。如果不是,它就是這樣。它是這樣的:

//DataClass.h

@interface DataClass : NSObject { 

NSMutableArray *nameArray; 
NSMutableArray *placeArray;  

} 
@property(nonatomic,retain)NSMutableArray *nameArray; 
@property(nonatomic,retain)NSMutableArray *placeArray; 
+(DataClass*)getInstance; 
@end 

//DataClass.m

@implementation DataClass 
@synthesize nameArray; 
@synthesize placeArray; 
static DataClass *instance =nil; 
+(DataClass *)getInstance 
{ 
    @synchronized(self) 
    { 
     if(instance==nil) 
     { 

      instance= [DataClass new]; 
     } 
    } 
    return instance; 
} 

現在在您的視圖控制器,你需要調用此方法爲:

DataClass *obj=[DataClass getInstance]; 

並使用數組。
這樣你就可以分配數據而不會打擾AppDelegate,這是一個很好的做法。

+0

好thx Nitish我試試這個 – user627441 2011-05-23 15:04:59

+0

是的。如果你發現它正確upvote答案並接受它:)) – Nitish 2011-05-23 15:06:31

+1

@Nitish我試圖用你的例子來創建一個數據類,以共享一個MainViewController和SecondViewController之間的日曆事件數組,這恰好發生是一個表格視圖。我如何去「設置」數組本身,以便通過DataClass * obj = [DataClass getInstance];'來訪問它? – jhilgert00 2012-10-26 03:26:03

相關問題