In my app I have a method that, when I press a button, adds a string to a NSMutableArray which is the model for a UITableView.
- (void)addPressed:(id)sender
{
NSString *string = @"aString";
[self.array addObject:string];
NSLog(@"Array count: %d",[self.array count]);
[self.tableView reloadData];
}
Problem is that the adding works the first time only if I press twice the button connected to this action I get this output:
2012-09-16 21:33:08.766 iUni[3066:c07] Array count: 1 //Which is fine since it worked
2012-09-16 21:33:08.952 iUni[3066:c07] Array count: 1 //Now count should be 2!!
Anyone has a guess on why is this happening?
I added the @property, synthesized it and lazy instatiated it this way:
- (NSMutableArray *)array
{
if (!_array) {
NSMutableArray *array = [NSMutableArray array];
_array = array;
}
return _array;
}
Your array is being created as an unowned (autoreleased, actually) object, which means that it is destroyed shortly after each time your accessor is called. It is then recreated the next time you access it, which gives you a new, empty array.
You need to create an owned version of the array to store into your instance variable:
You could also turn on ARC, which would have taken care of this for you and is a good idea anyways.