首先,您不能写入 mainBundle 中的任何内容。为了让您写信给您的 plist,您需要将其复制到文档目录。这样做是这样的:
- (void)createEditableCopyOfIfNeeded
{
// First, test for existence.
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writablePath = [documentsDirectory stringByAppendingPathComponent:@"Template.plist"];
success = [fileManager fileExistsAtPath:writablePath];
if (success)
return;
// The writable file does not exist, so copy from the bundle to the appropriate location.
NSString *defaultPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Template.plist"];
success = [fileManager copyItemAtPath:defaultPath toPath:writablePath error:&error];
if (!success)
NSAssert1(0, @"Failed to create writable file with message '%@'.", [error localizedDescription]);
}
因此调用此函数将检查文件是否存在于文档目录中。如果不是,它将文件复制到文档目录。如果文件存在,它只会返回。接下来,您只需要访问该文件即可对其进行读写。要访问您只需要文档目录的路径并将您的文件名添加为路径组件。
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [docDir stringByAppendingPathComponent:@"Template.plist"];
要从 plist 中获取数据:
NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:filePath];
将文件写回文档目录。
[array writeToFile:filePath atomically: YES];