我在创建使用 JSON 保存从 Web 服务接收的数据的 Plist 文件时遇到问题。无法创建 Plist 文件。路径为空,数据无处保存。当我清理派生数据时,出现了此问题。请为此提出任何解决方案。
JSON数据:
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];
}
谢谢。
您在评论中提到数据是从 Web 服务作为 JSON 获取的,然后转换为字典。
问题几乎可以肯定是您的 JSON 数据包含空值,这意味着您的字典包含 NSNull
的实例。不能将NSNull
写入此类文件,因为它不是属性列表类型之一。编写这样的文件仅适用于NSDictionary
、NSArray
、NSString
、NSData
、NSNumber
和NSDate
的实例。此外,任何字典键都必须是字符串。
如果存在NSNull
(或任何非属性列表类的实例),则像这样写入文件将失败。
您需要浏览数据并删除所有NSNull
实例,或者以其他方式写入文件。
这是最简单的方法:将您的字典添加到数组中:
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);
}
投票给我,如果它对你有帮助