Priyank Gandhi
Priyank Gandhi

Reputation: 646

*** -[__NSArrayM objectAtIndex:]: index 51 beyond bounds [0 .. 50] error when I use UIsearchbar and UItableview

 -(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
 {
if (searchText.length == 0)
    isActive = NO;
else
    isActive = YES;

NSMutableArray *tmpSearched = [[NSMutableArray alloc] init];
NSMutableArray *tmpSearchedNumber = [[NSMutableArray alloc]init];
NSUInteger count1=0;
//NSUInteger count2=0;

for(count1=0;count1<[tableStationData count] || [tableData count];count1++)
{
    NSRange range = [[tableStationData objectAtIndex:count1] rangeOfString:searchText options:NSCaseInsensitiveSearch];
    NSRange range1= [[tableData objectAtIndex:count1]rangeOfString:searchText options:NSCaseInsensitiveSearch];

    if(range.location !=NSNotFound || range1.location != NSNotFound)
    {
        [tmpSearchedNumber addObject:[tableStationData objectAtIndex:count1]];
        [tmpSearched addObject:[tableData objectAtIndex:count1]];
    }
}

where tableData Array size is : 2530 and same array size tableStationData. when i search on UISearchbar that coding gives error.

Upvotes: 0

Views: 286

Answers (3)

Prasad G
Prasad G

Reputation: 6718

The problem is in for loop. Suppose tableStationData has 15 elements, tableData has 10 elements. The loop is running up to count1 is 9, when count1 is 10 , loop is running but inside loop, [tableStationData objectAtIndex:count1] works fine and [tableData objectAtIndex:count1] does not work, tableData has only 10 elements and it doesn't have 11th element. So we gets error in this case like -[__NSArrayM objectAtIndex:]:.

for(count1=0;count1<[tableStationData count] || [tableData count];count1++)
{
    NSRange range = [[tableStationData objectAtIndex:count1] rangeOfString:searchText options:NSCaseInsensitiveSearch];
    NSRange range1= [[tableData objectAtIndex:count1]rangeOfString:searchText options:NSCaseInsensitiveSearch];
}

Upvotes: 0

Merlevede
Merlevede

Reputation: 8170

I would change this

for(count1=0;count1<[tableStationData count] || [tableData count];count1++)

for this

for(count1=0;count1<[tableStationData count] && count1<[tableData count];count1++)

EDIT: corrected the last line with rmaddy's ovservation.

The way you're using the loop condition will always be true if tableData has at least 1 element, and the loop will never exit.

Upvotes: 1

SomeGuy
SomeGuy

Reputation: 9690

In this line:

for(count1=0;count1<[tableStationData count] || [tableData count];count1++)

This part:

 || [tableData count]

will always be true if there is at least one element in your tableData array, so it will exceed your maximum from tableStationData

Upvotes: 0

Related Questions