应用程序在快速uisearchbar文本条目上崩溃

时间:2014-01-16 07:33:20

标签: ios iphone objective-c arrays uisearchbar

我的应用在快速输入UISearchBar时显示以下错误

Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex:]: index 206 beyond bounds [0 .. 13]

慢慢打字时,搜索工作正常

-(void)searchBar:(UISearchBar*)searchBar textDidChange:(NSString*)text
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

    if(text.length == 0)
    {
        isFiltered = FALSE;
    }
    else
    {
        filteredTableData = [[NSMutableArray alloc] init];
        sortedCustomerID= [[NSMutableArray alloc]init];
        sortedDefaultsShipingID=[[NSMutableArray alloc]init];

        isFiltered = true;
        if (text !=nil)
        {
            NSPredicate *predicate =[NSPredicate predicateWithFormat:@"lastName contains[cd] %@ ",text];
            [fetchedResultsController.fetchRequest setPredicate:predicate];
        }
        else
        {
            NSPredicate *predicate = [NSPredicate predicateWithFormat:@"All"];
            [fetchedResultsController.fetchRequest setPredicate:predicate];
        }
        NSError *error = nil;
        if (![[self fetchedResultsController] performFetch:&error])
        {
            // Handle error
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            exit(-1);  // Fail
        }
       _fetchedObjects = fetchedResultsController.fetchedObjects;

        for (int i =0 ; i<_fetchedObjects.count ; i ++)
        {
            [filteredTableData addObject:[[_fetchedObjects valueForKey:@"lastName"]objectAtIndex:i]];

            [sortedCustomerID addObject:[[_fetchedObjects valueForKey:@"customerID"]objectAtIndex:i]];
            [sortedDefaultsShipingID addObject:[[_fetchedObjects valueForKey:@"defaultShippingID"]objectAtIndex:i]];
          }
       }

       NSLog(@" name=%@ customerID=%@ shippingID=%@", filteredTableData,sortedCustomerID,sortedDefaultsShipingID);

        dispatch_async(dispatch_get_main_queue(), ^{
            // Return data and update on the main thread
            // Task 3: Deliver the data to a 3rd party component (always do on the main thread).

        });
    });
}

2 个答案:

答案 0 :(得分:2)

除了大多数例外情况,您都会获得相当多的其他信息,可以帮助您找出问题所在。

在这种情况下,异常描述告诉您您尝试访问不存在的NSArray元素。似乎有问题的NSArray对象是_fetchedObjects。此外,根据名称,它似乎是一个伊娃。

请考虑一下这里发生了什么。在搜索栏中输入字符。启动异步操作并检索数据,将其存储在_fetchedObjects中,然后进行访问。但是,如果很快创建了其中一些操作并且其中每个尝试访问相同的_fetchedObjects,会发生什么?

我会考虑将搜索结果存储在本地变量中,然后在异步操作结束时将其分配给ivar / property,如果你真的需要存储它。

答案 1 :(得分:0)

尝试将for循环更改为

for (int i =0 ; i<_fetchedObjects.count ; i ++)
{
        [filteredTableData addObject:[[_fetchedObjects objectAtIndex:i] valueForKey:@"lastName"]];
        [sortedCustomerID addObject:[[_fetchedObjects objectAtIndex:i] valueForKey:@"customerID"]];
        [sortedDefaultsShipingID addObject:[[_fetchedObjects objectAtIndex:i] valueForKey:@"defaultShippingID"]];
 }