Jeff Jeff - 1 year ago 59
Objective-C Question

Adding a row to a table in Objective-C

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;

[array release];

configListDataIndex ++;

I have been reading a lot about this stuff but this does not seem like it should be too hard. Also I feel that the main problem is that "array" only has one index and when the user tries to add another that is what makes the app crash.

Could someone please help me out and tell me what I am doing wrong and how I can do it right? Please!...Or maybe just point me in the right direction?

Answer Source

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;
    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

[array addObject:nameOfConfig];

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download