iOS NSMutableArray insertObject index out of bound
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 = addB开发者_开发问答utton;
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?
The call you make in insertRowsAtIndexPaths:withRowAnimation
: should be between a beginUpdates
and endUpdates
call on your tableView
.
Check the TableView Programming Guide.
The initWithCapacity method only sets aside memory for the objects, it does not actually create the number of objects specified in your array.
I am not sure if you can insert into an array that has no objects in it yet, so you might want to try to use the addObject method if the array count is 0, and the insertObject method otherwise.
精彩评论