在开发时在App bundle中以编程方式编辑plist



我在XCode上创建了一个plist,它将有一些我无法手动插入的值。所以我想在开发时以编程方式添加这些值。但似乎我只能读取plist,我不能保存plist在App bundle上,这在运行时是有意义的。当我分发我的应用程序时,我希望每个人都有这个plist文件,这就是为什么我不保存文档或缓存。我怎样才能实现我想要的?

从http://www.karelia.com/cocoa_legacy/Foundation_Categories/NSFileManager__Get_.m(粘贴在下面),您可以使用在那里找到的-(NSString *) pathFromUserLibraryPath:(NSString *)inSubPath方法在用户的个人库中构建路径。

例如,NSString *editedPlist = [self pathFromUserLibraryPath:@"my.plist"];获得用户库中修改的pllist的名称(即使该pllist还不存在)。

如何读/写它取决于你有什么样的plist,但是你可以用:

将它读到字典中。
NSMutableDictionary *thePlist= [[NSMutableDictionary alloc] initWithContentsOfFile:editedPlist ];

如果你不能读取,很容易被检测到,例如[thePlist count] == 0,那么你可以调用相同的initWithContentsOfFile:初始化器,在你的包中有一个模板的路径,但是你会把plist写出来到editedPlist路径,这样它就出现在用户目录中。


这是我上面提到的实用方法:

/*
    NSFileManager: Get the path within the user's Library directory
    Original Source: <http://cocoa.karelia.com/Foundation_Categories/NSFileManager__Get_.m>
    (See copyright notice at <http://cocoa.karelia.com>)
*/
/*" Return the path in the user library path of the given sub-path.  In other words, if given inSubPath is "foo", the path returned will be /Users/myUser/Library/foo
"*/
-  (NSString *) pathFromUserLibraryPath:(NSString *)inSubPath
{
    NSArray *domains = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask,YES);
    NSString *baseDir= [domains objectAtIndex:0];
    NSString *result = [baseDir stringByAppendingPathComponent:inSubPath];
    return result;
}

我建议在开始时编写检查文档目录中的plist的代码。如果有,读入内存

如果你在documents目录中找不到这个文件,那就从app bundle中读取它。然后从内存中插入使用它的代码,并将更改后的版本写入documents目录。

请记住,从plist文件中读取的所有对象都是不可变的,即使您将可变对象写入该文件。您必须编写代码,为您想要更改的任何内容创建可变副本。(如果你有复杂的结构,比如字典数组,而字典数组又包含字符串数组,那么就必须实现可变深度复制。)

最新更新