在开发时以编程方式编辑应用程序包中的plist

我已经在XCode上创build了一个plist,它有几个我不能手动插入的值。 所以我想在开发时以编程方式添加这个值。 但似乎我只能阅读plist我不能保存在应用程序包,这在运行时有意义的plist。当我将分发我的应用程序,我希望每个人都有这个plist文件,这就是为什么我不保存在文件或caching上。 我怎样才能达到我想要的?

http://www.karelia.com/cocoa_legacy/Foundation_Categories/NSFileManager__Get_.m (粘贴在下面),您可以在用户的​​个人库中build立一个path,并在那里find-(NSString *) pathFromUserLibraryPath:(NSString *)inSubPath方法。

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

你怎么读/写它是根据你有什么plist,但你可以阅读到一本字典:

 NSMutableDictionary *thePlist= [[NSMutableDictionary alloc] initWithContentsOfFile:editedPlist ]; 

如果你无法阅读,比如[thePlist count] == 0 ,那么你可以调用相同的initWithContentsOfFile:初始化程序,在你的包中有一个指向模板的path,但是你会把plist写出来editedPlistpath,使其出现在用户目录中。


这里是我上面引用的实用方法:

 /* 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; } 

我会build议编写代码,在开始时检查文档目录中的plist。 如果在那里,把它读入内存。

如果您在文档目录中找不到该文件,请改为从应用包中读取它。 然后放入从内存中使用它的代码,并将更改后的版本写入文档目录。

请记住,即使将可变对象写入文件,您从plist文件中读取的所有对象也都是不可变的。 你必须编写代码,使你想改变任何东西的可变副本。 (如果你有像字典数组这样的复杂结构,而这些结构又包含string数组,那么必须实现一个可变的深层拷贝。)