0

我是 iOS 新手。我最近遇到了一个问题。我有一个视图 A 和视图 B。视图 A 有一个导航控制器。视图 A 有一个按钮可以切换到 B。当我每次 B 创建一个新对象时单击此按钮时。我如何跟踪该对象以在这两个视图之间共享数据。谢谢

4

2 回答 2

2

有几种方法可以做到这一点。

您可以拥有 B 的属性,即 A 在您推动之前设置该属性。(NSDictionary、Array、String 等)这不是最好的方法,但它会起作用。

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 

在视图中,您可以使用它来获取指针。

-(AppData*)theAppData {

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

    return theData;
}

还有这个。

 appData = [self theAppData];

然后,您可以轻松访问 appData 的任何属性。

于 2013-05-09T15:58:30.870 回答
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
于 2013-05-09T15:44:02.537 回答