【问题标题】:NSRangeException for empty array except there is an array?空数组的NSRangeException,除了有一个数组?
【发布时间】:2012-06-22 01:54:34
【问题描述】:

我遇到了这个问题,我在控制台中不断收到此错误:

* 由于未捕获的异常“NSRangeException”而终止应用程序,原因:“* -[__NSArrayI objectAtIndex:]: index 0 beyond bounds for empty array”

这是我从 XML 文档中检索数据的代码:

CXMLDocument *worldweather = [[CXMLDocument alloc]initWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://free.worldweatheronline.com/feed/weather.ashx?q=%@&format=xml&num_of_days=4&key=0ded69e02b171832121504",query]] 选项:0 错误:无];

weathercondition = [[[worldweather nodesForXPath:@"/data/current_condition/weatherIconUrl" error:nil] objectAtIndex:0] stringValue];

Xcode 使用的位置是 Williams, CA,发送的查询是

威廉姆斯+CA

当我将它插入我的 URL 时,它可以工作并且我得到了我的 XML 文件,但是为什么我在我的控制台中得到这个消息???

这快把我逼疯了。非常感谢所有帮助!提前致谢!

【问题讨论】:

  • 让我知道如果你执行 NSLog(@"class: %@", [[worldweather nodesForXPath:@"/data/current_condition/weatherIconUrl" error:nil] class]);
  • 这是我现在的控制台:2012-06-19 20:17:38.441 Forecaster[10795:c07] Williams+CA 2012-06-19 20:17:38.799 Forecaster[10795:630b] () 2012-06-19 20:17:38.799 Forecaster[10795:630b] 数组中的元素:0 2012-06-19 20:17:38.800 Forecaster[10795:630b] *** 由于未捕获的异常“NSRangeException”而终止应用程序',原因:'*** -[__NSArrayI objectAtIndex:]:空数组的索引 0 超出范围'
  • 我知道,但是在你有天气条件之前添加 = ... 只需添加我的行 NSLog(@"class: %@", [[worldweather nodesForXPath:@"/data/current_condition/weatherIconUrl"错误:无] 类]);让我知道控制台现在输出什么
  • 我的错!对于那个很抱歉。这里是:2012-06-19 20:58:35.975 Forecaster[11460:5f0b] 类:__NSArrayI
  • 好的,现在用这个替换那个 NSLog: NSLog(@"array returned: %@", [worldweather nodesForXPath:@"/data/current_condition/weatherIconUrl" error:nil]);跨度>

标签: objective-c ios xml xml-parsing touchxml


【解决方案1】:

您似乎认为[worldweather nodesForXPath:@"/data/current_condition/weatherIconUrl" error:nil]NSArray 在数组中至少有一个对象。显然情况并非如此,并且您会收到一条错误消息,指出索引 0 处没有对象,这意味着该数组为空。

如果您不确定NSArray 中至少有一个对象,请不要只调用objectAtIndex:0

您可以先检查数组中有多少元素,然后执行以下操作:

NSArray *weatherArray = [worldweather nodesForXPath:@"/data/current_condition/weatherIconUrl" error:nil];

if ([weatherArray count] > 0){
  weathercondition = [[weatherArray objectAtIndex:0] stringValue];
}

如果您不确定从服务器返回什么,请查看数组中的内容:

NSLog(@"%@", weatherArray);

或检查有多少元素:

NSLog(@"elements in Array: %i", [weatherArray count]);

您可以使用的另一个有用的东西是例如[weatherArray lastObject],这将始终返回数组的最后一个元素,并且即使数组为空也将返回 nil(它不会像 objectAtIndex:0 那样崩溃)

【讨论】:

  • 让我抓狂的是,如果你把它放在 Safari 中:free.worldweatheronline.com/feed/…,就会有一个对象!不知道为什么说没有对象?它之前有效,然后现在随机这个 NSRangeException 即将到来
  • 如果您输入我在您的问题下方的评论中输入的内容,请告诉我您会得到什么...如果您不分享一些信息,我将无法帮助您
  • 我解决了。原来查询来自另一个视图控制器,所以在你帮助我之前我所做的所有查询编辑都无济于事。我非常感谢你的帮助。我确实学到了一些调试代码的新方法!谢谢!
猜你喜欢
  • 1970-01-01
  • 2021-05-30
  • 1970-01-01
  • 2019-12-29
  • 2018-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-19
相关资源
最近更新 更多