我在plist中保存了很多信息。这个是我的mainBundle中的标准。
这是我从plist加载路径和数据的方法。如果“应用程序支持”文件夹中的文件不存在,我将它从mainBundle复制到那里。
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
self.plistPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist",plistName]];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: self.plistPath])
{
NSString *pathInBundle = [[NSBundle mainBundle] pathForResource:plistName ofType:@"plist"];
self.plist = [NSMutableDictionary dictionaryWithContentsOfFile:pathInBundle];
NSLog(@"plist doesnt exist");
}
else {
self.plist = [NSMutableDictionary dictionaryWithContentsOfFile:self.plistPath];
NSLog(@"plist exist");
}
NSLog(@"plist path: %@",self.plistPath);
如果我在最后添加以下行,则只有NO
答案:
if([fileManager isWritableFileAtPath:self.plistPath]) NSLog(@"YES");
else NSLog(@"NO");
毕竟,我试图用[self.plist writeToFile:self.plistPath atomically:YES];
保存,这也无法正常工作。
NSMutableDictionary *updateDict = [[self.plist objectForKey:@"comments"]mutableCopy];
NSMutableDictionary *tmpDict = [[[NSMutableDictionary alloc]init]autorelease];
[tmpDict setObject:comment forKey:@"comment"];
[tmpDict setObject:author forKey:@"author"];
[tmpDict setObject:car forKey:@"car"];
[tmpDict setObject:part forKey:@"part"];
[tmpDict setObject:date forKey:@"date"];
[updateDict setObject:tmpDict forKey:[NSNumber numberWithInt:[updateDict count]+1]];
[self.plist setObject:updateDict forKey:@"comments"];
if([self.plist writeToFile:self.plistPath atomically:YES]) {
return YES;
}
else {
return NO;
}
self.plist是plistPath上文件的本地副本。我的plist的结构如下:https://img.skitch.com/20111026-tcjxp9ha4up8ggtfjy7ucgqcqe.png
希望这会有所帮助
答案 0 :(得分:1)
好的,所以这不是Documents目录,默认情况下iOS没有在沙箱中创建的Application Support目录,这就是你不能写的原因。
您可以更改方法调用以查找真实文档目录:
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
或者,在获得 Application Support 目录的路径后,您必须检查它是否已存在,如果不存在,则创建它。
答案 1 :(得分:0)
请浏览previous post,其中显示了从mainBundle复制plist的不同方法。改为使用[fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
方法。
答案 2 :(得分:0)
你找到了答案吗?如果没有,您需要更改此行:
[updateDict setObject:tmpDict forKey:[NSNumber numberWithInt:[updateDict count]+1]];
到
[updateDict setObject:tmpDict forKey:[NSString stringWithFormat:@"%d",[updateDict count]+1]];
键名是字符串,而不是对象。