我想将NSMutableArray
或NSDictionary
保存为永久文件。然后,我想稍后重新打开该文件。
这可能吗?如果是这样,我该怎么做?
答案 0 :(得分:51)
写入文件
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *filePath = [documentsDirectory stringByAppendingPathComponent:FILE_NAME]; [myArray writeToFile:filePath atomically:YES];
从文件中读取
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *filePath = [documentsDirectory stringByAppendingPathComponent:FILE_NAME]; myArray = [NSArray arrayWithContentsOfFile:filePath];如果文件不存在,
myArray将为nil。 NSDictionary有类似的方法。请查看参考资料以了解这些方法的详细信息。
答案 1 :(得分:2)
可以将Dictionary转换为JSON数据并将其写入文件。
NSDictionary *dict = /* the NSDictionary/NSArray you need to write */
NSError *writeError = nil;
NSData* data;
data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&writeError];
if (!writeError) {
[data writeToFile:filePath atomically:YES];
}