2013-05-09 47 views
0

我是iOS的新手。我最近陷入了一個問題。 我有一個視圖A和視圖B.視圖A有一個導航控制器。視圖A有一個按鈕可以切換到B.當我每次B創建一個新對象時單擊此按鈕。我如何跟蹤這個對象在這兩個視圖之間共享數據。 謝謝對象在iOS中的視圖之間創建視圖和共享數據

+0

你是什麼意思你想跟蹤視圖? – Mohith 2013-05-09 15:39:45

+0

你想將數據從A傳遞給B嗎? – Mohith 2013-05-09 15:40:09

+0

您應該在斯坦福iOD課程中觀看第7講的開始:https://itunes.apple.com/us/course/coding-together-developing/id593208016 – 2013-05-09 16:11:31

回答

2

有幾種方法可以做到這一點。

您可以擁有B的屬性,A在您推送之前設置。 (NSDictionary,數組,字符串等) 這不是最好的方式,但它會工作。

UIViewController *viewB = [[UIViewController alloc]init]; 
[viewB setMyProperty:@"some data!"]; 
[self.navigationController pushViewController:viewB animated:YES]; 

您也可以使用NSNotificationCenter將對象傳遞到下一個視圖。

NSDictionary *dictionary = [NSDictionary dictionaryWithObject: 
         [NSNumber numberWithInt:index] 
         forKey:@"index"]; 

[[NSNotificationCenter defaultCenter] postNotificationName:@"myNotification" 
             object:self 
             userInfo:dictionary]; 

我通常處理這個問題的方法是設置且與在我的AppDelegate初始化的相關聯的協議保持我的數據對象。然後任何需要讀取/寫入東西的視圖都會抓取一個指向該對象的指針並與其一起運行。

@class AppData; 

@protocol AppDataProtocol 

- (AppData*)theAppData; 

@end 

在View中你可以用這個指針抓住這個指針。

-(AppData*)theAppData { 

    id<AppDataProtocol> theDelegate = (id<AppDataProtocol>)[UIApplication sharedApplication].delegate; 
    AppData* theData = (AppData*)theDelegate.theAppData; 

    return theData; 
} 

和這個。

appData = [self theAppData]; 

然後,您可以輕鬆訪問appData的任何屬性。

0
-(void)fnButtonA{ 

ViewB *vcB = [[ViewB alloc] initWithData:DataToB]; 
[[self navigationController] pushViewController:vcB animated:Yes]; 

} 


In ViewB.m edit the init function to 

-(UIViewController *)initWithData:(NSMutableDictionary*)data 
相關問題