简体   繁体   中英

How to add to an array from a separate view controller

I have an array players in a view controller SearchViewController , and I also have a multitude of other view controllers, which have text fields such as: textFieldOne and textFieldTwo .

How can I insert the text in textFieldOne to the players array from a view controller other than SearchViewController ?

You're violating the MVC design pattern by having the players array in SearchViewController, and you can see how this complicates your life. If you followed the pattern, you'd have your players array in a separate model class. You should create an instance of this class then pass it around to the various view controllers that need to interact with it. If you use Key-Value Observing (KVO) on the model properties, all your view controllers can be notified when one of them changes it. So if view controller A adds a new player, view controller B could update its table view list of player names, for instance.

The simplest method to do this is using, NSNotification with userInfo.

Add the observer in the view controller , where the updates need to be made.

[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(updateArray:) name:@"updateArray" object:nil];

Write the method,

-(void)updateArray:(NSNotification*)notif
{
[[NSNotificationCenter defaultCenter]removeObserver:self name:@"updateArray" object:nil];

    NSDictionary *dictionary = [notif userInfo];
    [self.arrPlayers addObject:dictionary];
}

And then, post notification wherever, the updates need to be called from ->

    NSString *notificationName = @"updateArray";
    NSString *key = txtField.text;
    NSDictionary *dictionary = [NSDictionary dictionaryWithObject:orientation forKey:key];
    
[[NSNotificationCenter defaultCenter] postNotificationName:notificationName object:nil userInfo:dictionary];

TRY IT !!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM