因未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'data parameter is nil'

时间:2014-06-25 09:11:54

标签: ios objective-c

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

  

NSInvalidArgumentException',原因:'data parameter is nil'

这是我的编码:

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];
}

3 个答案:

答案 0 :(得分:2)

我怀疑"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对象。

答案 1 :(得分:2)

问题是这段代码:

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

发送网址请求时,您应始终预计会出现问题。这有很多原因。在这种情况下,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];

答案 2 :(得分:0)

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