开发者

iPhone: Error and error handling confusion in comparison

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 boun开发者_开发知识库ds (0)

The results array being null should be accounted for during the checks in the above code, no?


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜