[英]Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'UICollectionView must be initialized with a non-nil layout parameter
[英]Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'data parameter is nil'
运行应用程序时,我正在使用Web服务开发应用程序,但它得到了响应,但有时会崩溃并显示如下错误:
NSInvalidArgumentException”,原因:“数据参数为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];
}
我怀疑"headline"
对象并不总是可用; 防止使用以下内容:
for (int i=0; i<[headlinetop count]; i++)
{
NSString *headstr=[[headlinetop objectAtIndex:i]objectForKey:@"headline"];
if (headstr)
[loadingcell addObject:headstr];
}
如果loadcell
是Objective-C集合类,则它将反对headstr
为nil
因为它们不能存储NULL对象。
问题是此代码:
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSDictionary *jsonArray=[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&err];
发送URL请求时,您始终应该期望出现问题。 原因有很多。 在这种情况下, responseData
为nil
。 NSJSONSerialization
期望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];
我认为您的问题是您正在使用的网址。 请检查以下链接: “ NSInvalidArgumentException”,原因:“数据参数为nil”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.