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