[英]Edit Programmatically plist in the App bundle at development time
我在XCode上创建了一个plist,它将具有一些我无法手动插入的值。 因此,我想在开发时以编程方式添加此值。 但似乎我只能读取plist,但我无法保存App捆绑包中的plist,这在运行时很有意义。.当我分发我的应用程序时,我希望每个人都拥有这个plist文件,这就是为什么我不保存在文档或缓存上。 我怎样才能实现自己想要的?
在http://www.karelia.com/cocoa_legacy/Foundation_Categories/NSFileManager__Get_.m (粘贴在下面)中,您可以使用-(NSString *) pathFromUserLibraryPath:(NSString *)inSubPath
方法在用户的个人库中构建路径。
例如, NSString *editedPlist = [self pathFromUserLibraryPath:@"my.plist"];
获取用户库中经过修改的plist的名称(即使该plist尚不存在)。
根据您拥有哪种类型的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目录中找不到该文件,请改为从应用程序捆绑包中读取。 然后从内存中放入使用它的代码,并将更改的版本写入documents目录。
请记住,即使您将可变对象写入文件,从plist文件读取的所有对象也将被视为不可变的。 您必须编写代码,使要更改的任何内容都可变。 (如果您有复杂的结构(如字典数组,又包含字符串数组),则必须实现可变的深层副本。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.