[英]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.