user2569812 user2569812 - 5 months ago 26
Objective-C Question

UITableView index beyond bounds error

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
{
}

Answer

I would change your settings to be initialized like this:

- (void)viewDidLoad
{
    [super viewDidLoad];
    settingTable.delegate = self;
    settingTable.dataSource = self;
}

- (NSMutableArray *)settings
{
    if (!_settings) settings = [[NSMutableArray alloc] initWithObjects:@"Downloads", @"Queue", @"FAQ", nil];
    return _settings;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return settings.count;
}

This way your settings object is always initialized.

Comments