首先,您无法写入任何内容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];
没有成功仍然获得数组的空值,我已经添加了你的方法 - (void)createEditableCopyOfIfNeeded,然后从视图DidLoad调用它作为[self createEditableCopyOfIfNeeded],调用此函数后,我已经使用你的代码读取plist文件但得到空值 – 2012-02-09 09:35:49
我曾遇到过这个问题。你可能需要做的是重置模拟器。这段代码所做的是,如果有一个名为Template.plist的文件,它将不会覆盖它。所以如果文件已经存在,那么这个代码将不会为你工作,直到你删除它。通过运行模拟器并点击iOS模拟器菜单并按下重置内容和设置,即可完成此操作。这将擦拭模拟器清洁。其他选项是使用NSLog(@“%@”,filePath);然后按照路径直到找到文件并将其删除。 – Jaybit 2012-02-09 15:59:03