我在视图控制器SearchViewController中有一个数组players,还有许多其他视图控制器,它们都有文本字段,比如:textFieldOne和textFieldTwo。
如何将textFieldOne中的文本从SearchViewController以外的视图控制器插入到players数组中?
发布于 2013-08-01 01:27:13
将播放器数组放在SearchViewController中违反了MVC设计模式,您可以看到这会使您的生活变得复杂。如果你遵循这个模式,你会在一个单独的模型类中拥有你的玩家数组。您应该创建此类的一个实例,然后将其传递给需要与其交互的各种视图控制器。如果您在模型属性上使用键值观察(KVO),则当其中一个视图控制器发生更改时,可以通知所有视图控制器。因此,如果视图控制器A添加了一个新玩家,则视图控制器B可以更新其表视图中的玩家名称列表,例如。
发布于 2013-08-01 19:32:08
要做到这一点,最简单的方法是使用带有userInfo的NSNotification。
在需要进行更新的视图控制器中添加观察者。
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(updateArray:) name:@"updateArray" object:nil];编写方法,
-(void)updateArray:(NSNotification*)notif
{
[[NSNotificationCenter defaultCenter]removeObserver:self name:@"updateArray" object:nil];
NSDictionary *dictionary = [notif userInfo];
[self.arrPlayers addObject:dictionary];
}然后,在需要从->调用更新的地方发布通知
NSString *notificationName = @"updateArray";
NSString *key = txtField.text;
NSDictionary *dictionary = [NSDictionary dictionaryWithObject:orientation forKey:key];
[[NSNotificationCenter defaultCenter] postNotificationName:notificationName object:nil userInfo:dictionary];试试吧!!
https://stackoverflow.com/questions/17976824
复制相似问题