0

I'm using an NSMutableArray to populate cells in my tableview. The problem is, when I try adding an object to my array, it replaces all the objects with the one that was added so I always only have 1 object in my array. Because of this, my tableview always has one cell that is just overwritten whenever the below method is called. Am I missing something?

_selectedThingArray = [[NSMutableArray alloc] init];

_currentThing = newThing;
//Note: newThing is the object being passed when this method is called. 
//It is the new data that will should passed into the cell.

[_selectedThingArray addObject:_currentThing];

NSLog(@"%@", newThing);
NSLog(@"array: %@", _selectedThingArray);

[self.tableView reloadData];
8
  • Are you sure you r not modifying your array somewhere else in ur code? Commented Aug 25, 2013 at 13:41
  • I think that you just recreate your array in the method which adds object... _selectedThingArray = [[NSMutableArray alloc] init]; , move creating to init method Commented Aug 25, 2013 at 13:42
  • You're initing _selectedThingArray every time the above is called. Oddly, this means it will only ever contain one item. Commented Aug 25, 2013 at 13:43
  • 1
    Why on earth are you allocating the array again, if you want to keep the previous set of items in the selectedthingsarray? _selectedThingArray = [[NSMutableArray alloc] init]; Do this if(!_selectedThingArray) _selectedThingArray = [[NSMutableArray alloc] init]; Commented Aug 25, 2013 at 13:43
  • 2
    Then you should not allocate the array everytime in delegate method. You can see others answers - they are all right Commented Aug 25, 2013 at 13:48

2 Answers 2

7

Is this line:

_selectedThingArray = [[NSMutableArray alloc] init];

executed every time you "try adding an object"? If yes, then this is your problem. Instead of adding an object to an existing array, you replace it with a brand new array and add object to this new array.

You need to either create the array at some point before you “try adding an object”, or create the array in the same place you're doing it now, but only when you have not already created one.

Sign up to request clarification or add additional context in comments.

Comments

2

Add this if condition before allocation:

if(!_selectedThingArray) 
_selectedThingArray = [[NSMutableArray alloc] init];

Instead of this only:

_selectedThingArray = [[NSMutableArray alloc] init];

Everything will be fixed.

1 Comment

Not everything. But it will not appear to fail in the short run.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.