0

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?

2 Answers 2

2

The call you make in insertRowsAtIndexPaths:withRowAnimation: should be between a beginUpdates and endUpdates call on your tableView.

Check the TableView Programming Guide.

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

Comments

0

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.

1 Comment

Thanks, that kinda helped. But now I get same error, but 2 lines below. Any ideas what's wrong with it?

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.