【问题标题】:Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'data parameter is nil'由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“数据参数为零”
【发布时间】:2014-06-25 17:38:46
【问题描述】:

我在运行应用程序时使用 Web 服务开发应用程序,它得到响应,但有时它崩溃并显示如下错误:

NSInvalidArgumentException',原因:'数据参数为零'

这是我的代码:

NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://api.espn.com/v1/sports/tennis/news/headlines?apikey=th98vzm67pufc36ka42xxxmy"]];
[request setHTTPMethod:@"GET"];
[request setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"content-type"];

NSError *err;
NSURLResponse *response;

NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSDictionary *jsonArray=[NSJSONSerialization JSONObjectWithData:responseData  options:NSJSONReadingMutableContainers error:&err];
NSArray *headlinetop=[jsonArray objectForKey:@"headlines"];

for (int i=0; i<[headlinetop count]; i++)
{
    NSString *headstr=[[headlinetop objectAtIndex:i]objectForKey:@"headline"];
    [loadingcell addObject:headstr];
}

【问题讨论】:

  • 那么记录responseDataerr...呢?是否只有一个 URL 的数据为零?
  • 我得到了很好的响应,但有时它会像这样崩溃
  • 好吧,当它崩溃时,检查err 可能会很有趣。我会使用另一个NSError,而不是使用两次err。不检查它们,就像把 nil 代替。

标签: ios objective-c


【解决方案1】:

我怀疑"headline" 对象并不总是可用的;防止使用:

for (int i=0; i<[headlinetop count]; i++)
{
    NSString *headstr=[[headlinetop objectAtIndex:i]objectForKey:@"headline"];
    if (headstr)
        [loadingcell addObject:headstr];
}

如果loadcell 是一个Objective-C 集合类,它将反对headstrnil,因为它们不能存储NULL 对象。

【讨论】:

  • 加载单元是可变数组
【解决方案2】:

问题是这段代码:

NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSDictionary *jsonArray=[NSJSONSerialization JSONObjectWithData:responseData  options:NSJSONReadingMutableContainers error:&err];

发送 URL 请求时,您应该始终认为会出现问题。有很多原因。在这种情况下,responseDatanilNSJSONSerialization 期望 data arg 不是 nil:错误。

收到请求的响应时,您应该始终检查它是否为nil。总是。

所以代码应该是这样的:

NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
if (responseData == nil)
{
  //  Maybe logging. But getting nil as a response of a URL request isn't exciting.
  return; // or whatever you have to (not) do
}
NSDictionary *jsonArray=[NSJSONSerialization JSONObjectWithData:responseData  options:NSJSONReadingMutableContainers error:&err];

【讨论】:

    【解决方案3】:

    我认为您的问题是您正在使用的 Url。 请检查以下链接: 'NSInvalidArgumentException', reason: 'data parameter is nil'

    【讨论】:

      猜你喜欢
      • 2018-04-05
      • 2013-04-27
      • 2021-09-17
      • 2012-07-12
      • 2021-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多