[英]-[NSDictionary dictionaryWithContentsOfFile] returning nil on iPad; returning dictionary in the simulator
[英]dictionaryWithContentsOfFile Returns Nil rather the NSdictionary
我創建了一個名為Dict.json的文件。該文件的內容為有效的json包含
{“ mydata”:[{“ A”:4,“ B”:14,“ C”:7},{“ A”:4,“ B”:12,“ C”:7},{“ A” :34,“ B”:154,“ C”:6},{“ A”:34,“ B”:162,“ C”:6}]}
我想從該文件創建一個NSDictonary。我嘗試了以下操作,但返回nil。
NSString * filePath = [[NSBundle mainBundle] pathForResource:@“ Dict” ofType:@“ json”]; NSMutableDictionary * newArr1 = [NSMutableDictionary dictionaryWithContentsOfFile:filePath];
我還在檢查文件是否為nil;
NSData *myData = [NSData dataWithContentsOfFile:filePath];
if (myData) {
NSLog("There is Data in File !!!!")
}
為了加載json
數據,您將需要NSJSONSerialization
來從文件中獲取json
數據。
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Dict" ofType:@"json"];
NSData *jsonData = [NSData dataWithContentsOfFile:filePath];
NSMutableDictionary *dic1 = [[NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil] mutableCopy];
您的代碼僅適用於plist
文件,不適用於json
文件。
從文檔中
+ (id)dictionaryWithContentsOfFile:(NSString *)path
參數
路徑
完整或相對路徑名。 路徑標識的文件必須包含屬性列表的字符串表示形式,該屬性列表的根對象是字典。
返回值
一個新的字典,該字典在path處包含該字典;如果存在文件錯誤或文件內容是字典的無效表示,則為nil。
如上所述,您只能使用plist文件(而不是來自.json + (id)dictionaryWithContentsOfFile:(NSString *)path
創建字典+ (id)dictionaryWithContentsOfFile:(NSString *)path
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.