快速键入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).
});
});
}
最佳答案
除了大多数例外情况,您会获得很多其他信息,可以帮助您找出问题所在。
在这种情况下,异常描述告诉您您尝试访问的NSArray
元素不存在。所讨论的NSArray
对象似乎是_fetchedObjects
。此外,根据名称,它似乎是一个ivar。
因此,请考虑这里发生了什么。在搜索栏中输入字符。启动异步操作,并检索数据,将其存储在_fetchedObjects
中,然后进行访问。但是,当其中几个操作很快被创建并且每个操作都尝试访问相同的_fetchedObjects
时,会发生什么情况?
我会考虑将搜索结果存储在本地变量中,然后在确实需要存储的情况下,将其分配给异步操作末尾的ivar /属性。
关于ios - 应用程序在快速uisearchbar文本输入时崩溃,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21155836/