I'm new to Objective-C programming so sorry for the lame question.
I'm trying to write some simple app that would add single numbers stored in the NSMutableArray to the table view.
Here is the init code and code for addItem() method:
- (void)viewDidLoad {
[super viewDidLoad];
self.title = @"Test App";
self.navigationItem.leftBarButtonItem = self.editButtonItem;
addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addItem)];
self.navigationItem.rightBarButtonItem = addButton;
self.itemArray = [[NSMutableArray alloc] initWithCapacity:100];
}
- (void)addItem {
[itemArray insertObject:@"1" atIndex:0];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
This line
[itemArray insertObject:@"1" atIndex:0];
produces following error:
*** -[NSMutableArray objectAtIndex:]: index 0 beyond bounds for empty array'
Why index 0 is beyond bounds for empty array and what I'm doing wrong???
UPD
As BP pointed out, insertion into array might not work for empty array, so I added following check:
if ([itemArray count] == 0) {
[itemArray addObject:@"1"];
} else {
[itemArray insertObject:@"1" atIndex:0];
}
So now I get same error message, but at line
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
Any ideas on what might be wrong with it?