Ios – UITableView index beyond bounds error

iosobjective c

I am experiencing an error at the following line:

cell1.textLabel.text = [settings objectAtIndex:indexPath.row];

And this is the uncaught inception error i receive:

Terminating app due to uncaught exception 'NSRangeException',
    reason: '-[__NSArrayM objectAtIndex:]: index 3 beyond bounds [0 .. 2]'
First throw call stack:
(0x2265012 ... 0x21a5 0x1)
libc++abi.dylib: terminate called throwing an exception
(lldb)

Here's my code:

.h:

@interface ViewController : UIViewController <UITableViewDataSource ,UITableViewDelegate>{

    //Settings Table
    IBOutlet UITableView *settingTable;
    NSMutableArray *settings;
}

@property (nonatomic, retain) UITableView *settingTable;
@property (nonatomic, retain) NSMutableArray *settings;

.m:

@synthesize settingTable;
@synthesize settings;

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (!settings) {
        return 0;
    }

    if ([settings count] > 0){
        return [settings count];
    }
    else
        return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (settingTable) {

        NSLog(@"%@", settings);

        UITableViewCell *cell1 = [settingTable dequeueReusableCellWithIdentifier:@"MainCell1"];
        if (cell1 == nil) {
            cell1 = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MainCell1"];
        }

        cell1.textLabel.text = [settings objectAtIndex:indexPath.row];
        return cell1;
   }

// ...

- (void)viewDidLoad
{
    [super viewDidLoad];

    settingTable.delegate = self;
    settingTable.dataSource = self;

    //settings table
    settings = [[NSMutableArray alloc] initWithObjects:@"Downloads", @"Queue", @"FAQ", nil];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}

Best Answer

The problem is that you are using static cells in UITableView. Just increase number of rows in your storyboard. It is the maximum count of cell you can add to Table View programmatically.

Sorry i didn't see that you're not using storyboard. But my answer is correct for those who are using it.

Related Topic