我正在尝试找出保存数据的最佳方式。
像这样将数据保存到plist有什么关系
NSString *error;
NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *plistPath = [rootPath stringByAppendingPathComponent:@"yourFile.plist"];
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:rootObj
format:NSPropertyListXMLFormat_v1_0
errorDescription:&error];
if(plistData) {
[plistData writeToFile:plistPath atomically:YES];
}
else {
NSLog(@"Error : %@",error);
[error release];
}
或者使用 NSData
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:FILE_NAME];
[myArray writeToFile:filePath atomically:YES];
我正在处理小型 XML 文件(我将其解析为 NSDictionaries)和大型 MP4 视频。对于我应该使用这两种文件存储方法中的哪一种,有什么建议吗?谢谢
最佳答案
我会选择 [myArray writeToFile:filePath atomically:YES];
(快速、简单、代码更少)
但只有当你的 NSArray
或 NSDictionaries
只包含非自身对象时(只包含 NSNumber
, NSString
, NSArray
等)。
如果您使用 NSPropertyListSerialization
,您应该使用选项 NSPropertyListBinaryFormat_v1_0
。它速度更快,文件更小。
但是您还需要考虑解析 XML 然后存储到 XML Plist 中是否有意义。 :) 是的。这是有道理的,因为这样您就可以更轻松地处理它们。
您还可以考虑解析您的 XML 并将其存储在 CoreData 数据库中。然后,它使查询更加容易。
我也会将 MP4 视频存储在 NSDocumentDirectory 中。
关于ios 保存在 plist 中 vs 保存在 nsdata 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10196142/