Reputation: 4887
NSArray *results = [managedObjectContext executeFetchRequest:request error:&error];
if(results == nil){
NSLog(@"No results found");
searchObj = nil;
}else{
if ([[[results objectAtIndex:0] name] caseInsensitiveCompare:passdTextToSearchFor] == 0) {
NSLog(@"results %@", [[results objectAtIndex:0] name]);
searchObj = [results objectAtIndex:0];
}else {
NSLog(@"No results found");
searchObj = nil;
}
}
The code above compares data a user enters to data pulled from a database. If I enter data which is in the database; it works. But if I enter complete gibberish it returns the error below instead of "No results found."
*** WebKit discarded an uncaught exception in the webView:shouldInsertText:replacingDOMRange:givenAction: delegate: <NSRangeException> *** -[NSCFArray objectAtIndex:]: index (0) beyond bounds (0)
The results array being null should be accounted for during the checks in the above code, no?
Upvotes: 0
Views: 838
Reputation: 48460
You are potentially throwing an exception on the following line of code:
if ([[[results objectAtIndex:0] name] caseInsensitiveCompare:passdTextToSearchFor] == 0)
If the array is initialized and has zero elements, you'll pass the nil check, but you'll throw an exception when trying to access any objects within the array itself.
- (NSArray *)executeFetchRequest:(NSFetchRequest *)request error:(NSError **)error
can return an empty array. You should use NSArray's count
method instead of checking to see if the array is nil.
I recommend you set a breakpoints on objc_exception_throw and [NSException raise] as well to aid you in debugging your applications. Then run a backtrace in gdb to see where the exception is being thrown to further diagnose the real problem.
Chris Hanson has a great writeup on how to accomplish they above located here
Upvotes: 3