Search code examples
objective-cuitableviewviewdidload

NSMutableArray keeps multiplying/resetting


So I am making a simple app in Objective-C with a single tableview that will display airports and their associated airport codes, as well as allow the user to add new airports.

I have created a class of known airports and their codes in an NSArray to set the initial tableview data with the known airports. In viewDidLoad, I set a local NSMutableArray equal to the known airports array

- (void)viewDidLoad {
    [super viewDidLoad];

    self.allAirports = [[GGAirportData knownAirports] mutableCopy];

}

In a separate ViewController, an airport and its data can be added to this array through delegate methods, but as you can probably guess, every time the app boots up, having this code in viewDidLoad not only resets my NSMutableArray *allAirports to only the *knownAirports array, but once I implement NSUserDefaults to retain the added airports, it doubles the amount of airports in the original self.allAirports array....so the third airport I add, it triples it and so on....

So my question is, how can I bring the knownAirports data into this application without it multiplying every time? Where else can I declare and set these values other than viewDidLoad where it will only evaluate one time and never look back at the knownAirports array ever again? I have been on this bug for 3 days now and have tried every workaround I can think of. Thanks in advance


Solution

  • In your viewDidLoad you can check if the array of airports already exists in NSUserDefaults.

    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSArray *airportArray = [userDefaults arrayForKey:@"allAirports"];
    
    if(airportArray == nil) {
    
        // airports array doesn't exist, create new one from default
        self.allAirports = [[GGAirportData knownAirports] mutableCopy];
        // save
        [userDefaults setObject:self.allAirports forKey:@"allAirports"];
    }
    
    else {
    
        //airports array already exists, use it instead of default
        self.allAirports = [airportArray mutableCopy];
    }
    

    Now you are free to edit self.allAirports as much as you want.

    // assume GGAirport class exists and add a new instance to allAirports array
    GGAirport *newAirport = [[GGAirport alloc] initWithName:@"San Francisco International" code:@"SFO"];
    [self.allAirports addObject:newAirport];
    
    // save to user defaults
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:self.allAirports forKey:@"allAirports"];
    

    Keep in mind that later on when you retrieve the array from user defaults it will be an immutable array even though you saved a mutable one.