I am programming the search bar logic in an iOS application. I have 1 NSArray "results", which has the entities returned from a NSFetchRequest, and an empty NSMutableArray "resultados" where I want to add the objects returned from the first array.
Here's the code:
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString{
[self.resultados removeAllObjects];
NSFetchRequest *request = [NSFetchRequest alloc];
request.predicate = [NSPredicate predicateWithFormat:@"numero contains [cd] %@",searchString];
request.entity = [NSEntityDescription entityForName:@"Plaza" inManagedObjectContext:self.contexto];
NSSortDescriptor *ordenPorNumero = [[NSSortDescriptor alloc]initWithKey:@"numero" ascending:YES];
[request setSortDescriptors:[[NSArray alloc]initWithObjects:ordenPorNumero, nil]];
NSError *error = nil;
NSArray *results = [self.contexto executeFetchRequest:request error:&error];
if(error){
NSLog(@"Ha ocurrido un error: %@ %@",error,[error userInfo]);
abort();
}
[self.resultados addObjectsFromArray:results];
return YES;
}
Everytime this line is executed:
[self.resultados addObjectsFromArray:results];
I get the following exception:
2013-07-09 19:21:18.142 Actividad1[2347:c07] *** Terminating app due to uncaught exception NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 9 beyond bounds [0 .. 0]
I can't understand how can I go beyond any array bounds with the addObjectsFromArray method. In fact, if I replace this instruction for the following debug code which essentially does the same, I can see that I am adding all the objects, but always throw the exception when adding the last one, no matter how many objects the results return:
int num =0;
for(id i in results){
Plaza *p = i;
NSLog(@"%d - %@",num,p.numero);
num++;
[self.resultados addObject:i];
}
I've tried lots of variations, but I have no clue on what's going on.
Thanks in advance for your help.