I am new to objective-C and I'm having a lot of trouble trying to add new rows to a table. The way it is suppose to work is, when the app loads an alert pops up asking the user if they would like to, start a new configuration, load a saved configuration, or resume the last configuration. Now if they select start a new configuration, they will be asked to enter in the new name and when they tap done the app will save the new configuration in a table.
Right now I can only get the app to store just one configuration in the table, but if the user tries to make another new configuration then the app crashes.
Here is what my code looks like:
- (IBAction) testToAddToList
nameOfConfig = @"Test Name"; //this just bypasses the user from having to enter a name
NSMutableArray *array = [[NSMutableArray alloc] init];
[array insertObject:nameOfConfig atIndex:configListDataIndex];
self.configListData = array;
The problem, as Woofy mentions, is that you are creating a new array every time, instead of grabbing the previously created array. So, the first time you add to the array, you are basically doing:
[array insertObject:nameOfConfig AtIndex:0];
but on the next time, you create a brand new (empty) array, and the configListDataIndex variable is now 1, so you call
[array insertObject:nameOfConfig atIndex:1];
and crash, because 1 is out of bounds for an empty array. To solve this, you can do something like:
NSMutableArray *array; if (self.configListData != nil) // I know, unnecessary, but I like being explicit with my nil checks. array = self.configListData; else array = [NSMutableArray array];
Then don't release it at the end of the function (as I assume your getter for configListData is autoreleased, or assignment).
This will fix the crasher. Additionally, you can always just call
which automatically adds an object to the end of the array, so you can get rid of the index variable. But you should fix the crasher first, as changing this second part will just hide the bug, and make it even more mysterious that the new config just replaces the old one.