I have a UITableView whose data source is an NSMutableArray. The array contains NSMutableDictionaries with the keys “name”, “index”, “color”, and “string”. The index key represents the row in the table view the object is in. Moving and adding objects works fine with this and keeps them correct and updated, but when I try to delete an object, the “index” key of the objects after the deleted row are 1 off. I’ve tried many things, but every attempt has failed. Can someone give me some insite? Here is the code for the array:
contentarray = [[NSArray arrayWithObjects:
[NSMutableDictionary dictionaryWithObjectsAndKeys:
@"Object 1", @"name",
@"0", @"index",
@"0", @"color",
@"Example", @"string",
nil],
[NSMutableDictionary dictionaryWithObjectsAndKeys:
@"Object 2", @"name",
@"1", @"index",
@"1", @"color",
@"String 2", @"string",
nil],
[NSMutableDictionary dictionaryWithObjectsAndKeys:
@"Object 3", @"name",
@"2", @"index",
@"0", @"color",
@"String 3", @"string",
nil],
[NSMutableDictionary dictionaryWithObjectsAndKeys:
@"Object 4", @"name",
@"3", @"index",
@"2", @"color",
@"String 4", @"string",
nil],
[NSMutableDictionary dictionaryWithObjectsAndKeys:
@"Object 5", @"name",
@"4", @"index",
@"0", @"color",
@"String 5", @"string",
nil],
nil] mutableCopy];
Treating this problem more as an exercise (you wouldn’t store an index in an array element normally, there’s no need) I’ll provide a solution to the problem…
Firstly, you should probably be using NSNumber objects to represent numbers in an NSDictionary, so your array is full of dictionaries like so
Furthermore, I’d consider the use of a dictionary as a datatype fairly bad form, you’d be better off creating a class to represent whatever it is you’re storing here… however, to the solution of your question…
Once you’ve modified the array, you need to iterate through the array, updating the indices to their correct value as you go along. A function like the following would suffice: