繁体   English   中英

不能保存plist。 路径不可写

[英]can't save plist. path is not writable

我在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]; ,这也行不通。


很抱歉这么晚回答 - 我还有很多其他事要做。 回到我的问题:当我尝试向我的字典(plist)添加新条目时,我只得到错误。 编辑没问题。 我认为问题是,我如何尝试添加条目。 我的代码看起来像:

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

希望这可以帮助

好的,所以这不是Documents目录,默认情况下iOS没有在沙箱中创建的Application Support目录,这就是你不能写的原因。

您可以更改方法调用以查找真实文档目录:

NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

或者,在获得Application Support目录的路径后,必须检查它是否已存在,如果不存在,则创建它。

请仔细阅读上一篇文章 ,其中显示了从mainBundle复制plist的不同方法。 使用[fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error]; 方法而不是。

你找到了答案吗? 如果没有,您需要更改此行:

[updateDict setObject:tmpDict forKey:[NSNumber numberWithInt:[updateDict count]+1]];

[updateDict setObject:tmpDict forKey:[NSString stringWithFormat:@"%d",[updateDict count]+1]];

键名是字符串,而不是对象。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM