0

我使用 kumulos 访问数据库。这是我正在谈论的代码:

NSString *location = [[theResults objectAtIndex:0] objectForKey:@"location"];

现在,如果 [theResults objectatindex:0] 返回“null”,它每次都会崩溃,所以如果用户输入不在数据库中的内容,它就会崩溃,我想捕获这个异常(NSRange 异常)。

谢谢

4

2 回答 2

4

我认为这对你有用,不需要异常处理。

if ([theResults count] > 0) {
    NSString *location = [[theResults objectAtIndex:0] objectForKey:@"location"];
}

我假设这theResults是一个NSArray(或子类)。

于 2011-03-25T16:04:25.877 回答
1

要么检查 [theResults objectAtIndex:0] 不返回 nil,要么使用异常处理

@try {
   NSString *location = [[theResults objectAtIndex:0] objectForKey:@"location"];  
}
@catch (NSRangeEception * e) {
   NSLog(@"catching %@ reason %@", [e name], [e reason]);
}
@finally {
   //something that you want to do wether the exception is thrown or not.
}

不过,我建议至少学习一下这门语言,或者用谷歌练习:-)

于 2011-03-25T16:07:49.453 回答