2013-05-09 79 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