添加到一個數組我有一個視圖控制器SearchViewController
陣列players
,我也有其他視圖控制器,其具有文本字段如多種:textFieldOne
和textFieldTwo
。如何從單獨的視圖控制器
如何將textFieldOne
中的文本從SearchViewController
以外的視圖控制器插入players
陣列?
添加到一個數組我有一個視圖控制器SearchViewController
陣列players
,我也有其他視圖控制器,其具有文本字段如多種:textFieldOne
和textFieldTwo
。如何從單獨的視圖控制器
如何將textFieldOne
中的文本從SearchViewController
以外的視圖控制器插入players
陣列?
通過讓玩家陣列位於SearchViewController中,您正在違反MVC設計模式,並且您可以看到這會如何使您的生活變得複雜。如果你遵循這個模式,你可以將你的玩家陣列放在一個單獨的模型類中。你應該創建這個類的一個實例,然後將它傳遞給需要與之交互的各種視圖控制器。如果您在模型屬性上使用鍵值觀察(KVO),則可以在其中一個視圖控制器發生更改時通知所有視圖控制器。因此,如果視圖控制器A添加了新玩家,視圖控制器B可以更新其玩家名稱的表格視圖列表。
我不完全確定你的意思,對不起,我是面向對象編程的新手。感謝您的建議,我會嘗試閱讀您的建議。 – user2412643
閱讀MVC(模型/視圖/控制器)和KVO。你將不得不學習這些東西,否則你在iOS中的生活將會很困難。 – jsd
謝謝,我會做的。這似乎比我想象的要複雜得多。 – user2412643
最簡單的方法是使用NSNotification和userInfo。
添加觀察者在視圖控制器,其中需要進行更新。
[[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];
TRY IT!
其他視圖控制器是否有對「SearchViewController」實例的引用? –
@BrianNickel我將如何去引用它? – user2412643