我在项目中创建了一个plist文件。现在我想从应用程序中保存日期,并从中读取。为了做到这一点,我需要获取其位置和目录。这可能吗?
答案 0 :(得分:1)
由于您不仅要读取文件中的数据,还要写入文件,因此您需要将该文件复制到Documents目录中。可以这样做:
NSFileManager *fileManger=[NSFileManager defaultManager];
NSError *error;
NSArray *pathsArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *doumentDirectoryPath=[pathsArray objectAtIndex:0];
NSString *destinationPath= [doumentDirectoryPath stringByAppendingPathComponent:@"myDictionary.plist"];
if ([fileManger fileExistsAtPath:destinationPath]){
return;
}
NSString *sourcePath=[[[NSBundle mainBundle] resourcePath]stringByAppendingPathComponent:@"myDictionary.plist"];
[fileManger copyItemAtPath:sourcePath toPath:destinationPath error:&error];
您应该在应用程序启动时调用此代码。现在您可以获取plist并将其转换为字典:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filename = [documentsDirectory stringByAppendingPathComponent:[@"myDictionary" stringByAppendingPathExtension:@"plist"]];
NSMutableDictionary *plistDict;
if ([[NSFileManager defaultManager] fileExistsAtPath:filename]) {
plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
}
如果您现在要写信,请执行以下操作:
[plistDict setValue:@"value" forKey:@"key"];
BOOL didWriteToFile = [plistDict writeToFile:filename atomically:YES];
if (didWriteToFile) {
NSLog(@"Did Write!");
} else {
NSLog(@"Didn't write!");
}