无法创建Plist文件。iOS+;NSDictionary+;JSON
我在创建Plist文件时遇到问题,该文件使用JSON保存从web服务接收的数据。无法创建Plist文件。路径为空,数据不保存到任何位置。这个问题发生在我清理派生数据时。请对此提出任何解决方案 JSON数据:无法创建Plist文件。iOS+;NSDictionary+;JSON,ios,json,nsdictionary,plist,Ios,Json,Nsdictionary,Plist,我在创建Plist文件时遇到问题,该文件使用JSON保存从web服务接收的数据。无法创建Plist文件。路径为空,数据不保存到任何位置。这个问题发生在我清理派生数据时。请对此提出任何解决方案 JSON数据: eventID = 2356; eventName = "Testing Event"; 这是我在Plist中保存的方式: NSArray *eventsDictionary = [dataDictionary objectForKey:@"eventList"]; NSDictionar
eventID = 2356;
eventName = "Testing Event";
这是我在Plist中保存的方式:
NSArray *eventsDictionary = [dataDictionary objectForKey:@"eventList"];
NSDictionary *plistDict = [NSDictionary dictionaryWithObject:eventsDictionary
forKey:@"Events"];
if ([eventsDictionary count]==0) {
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
path = [path stringByAppendingPathComponent:DATA_DICTIONARY_KEY_USER_DEFAULTS];
[plistDict writeToFile:path atomically:YES];
}
else {
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
path = [path stringByAppendingPathComponent:DATA_DICTIONARY_KEY_USER_DEFAULTS];
[plistDict writeToFile:path atomically:YES];
}
多谢各位 以下是最简单的方法:
将dict添加到阵列:
NSMutableArray * mutArr = [NSMutableArray alloc]init];
[mutArr addObject:plistDict];
[self saveToPlistName:@"yourplist" fromArray:mutArr];
并使用这种方法
-(void)saveToPlistName:(NSString *)plistName fromArray:(NSMutableArray*)array
{
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentFolder = [path objectAtIndex:0];
NSString *filePath = [documentFolder stringByAppendingFormat:[NSString stringWithFormat:@"/%@.plist",plistName]];
[array writeToFile:filePath atomically:YES];
NSLog(@"SAVE SUCCESS TO DIRECTORY%@",filePath);
}
如果对您有帮助,请投我一票。您在评论中提到,数据以JSON的形式从web服务获取,然后转换为字典 几乎可以肯定的是,JSON数据包含空值,这意味着字典包含
NSNull
的实例。不能将NSNull
写入这样的文件,因为它不是属性列表类型之一。这样编写文件只适用于NSDictionary
、NSArray
、NSString
、NSData
、NSNumber
和NSDate
的实例。此外,任何字典键都必须是字符串
如果存在一个NSNull
(或任何非属性列表类的实例),那么像这样写入文件将失败
您需要遍历数据并删除所有
NSNull
实例,或者以其他方式写入文件。请发布确切的错误。1)为什么数组变量名为eventsDictionary
而不是eventsArray
?2) 为什么只有阵列为空时才保存文件?@rebello95,没有错误。无法创建Plist文件。我不明白为什么。即使是documents文件夹也没有plist文件。我假设DATA\u DICTIONARY\u KEY\u USER\u DEFAULTS
是无效路径,因此无法创建它。它的价值是什么?@rmaddy,1)我只是把它命名为eventsDictionary,我不认为这是原因。2) 这意味着如果“eventsDictionary”为空,则保存数据。仍然没有Plist文件。没错。但它非常奇怪,因为它以前是用空值保存的。无论如何,非常感谢您,先生:)