0

我想读/写 cache.plist

如果我想读取存储在资源文件夹中的现有预制 plist 文件,我可以去:

path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathWithComponent@"cache.plist"];
NSMutableDictionary *root = ...

但后来我想从 iPhone 上阅读它。

不能,资源文件夹是只读的。

所以我需要使用:

NSDocumentDirectory, NSUserDomain,YES

那么如何将我的 plist 文件预安装到文档目录位置呢?

因此,这意味着我不必在启动时处理复制 plist 文件的杂乱代码。(除非这是唯一的方法)。

4

3 回答 3

1

我知道这并不是您真正想要的,但据我所知,将文档放入 Documents 文件夹的唯一方法是将其实际复制到那里……但仅限于第一次启动时。我正在为 sqlite 数据库做类似的事情。代码如下,它可以工作,但请注意它可以做一些清理工作:

// Creates a writable copy of the bundled default database in the application Documents directory.
- (void)createEditableCopyOfDatabaseIfNeeded {
    // First, test for existence.
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"WordsDatabase.sqlite3"];
    createdDatabaseOk = [fileManager fileExistsAtPath:writableDBPath];
    if (createdDatabaseOk) return;
    // The writable database does not exist, so copy the default to the appropriate location.
    NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"WordsDatabase.sqlite3"];
    createdDatabaseOk = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
}

只需调用您的 AppDelegate - 真的不会太乱吗?

于 2010-05-18T06:45:42.500 回答
1

简单的。首先查看它是否在文档目录中。如果不是,请在应用程序的 Resources 文件夹 ( [[NSBundle mainBundle] pathForResource...]) 中找到它,然后使用 . 将其复制到文档目录中[[NSFileManager defaultManager] copyItemAtPath:...]。然后不受惩罚地使用文档目录中的新副本。

于 2010-05-18T06:45:59.790 回答
1

最终产品

NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathComponent:@"Cache.plist"];


NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *giveCachePath = [documentsDirectory stringByAppendingPathComponent:@"Cache.plist"];


BOOL fileExists = [fileManager fileExistsAtPath:giveCachePath];

if (fileExists) {
    NSLog(@"file Exists");
}
else {
    NSLog(@"Copying the file over");
    fileExists = [fileManager copyItemAtPath:finalPath toPath:giveCachePath error:&error];
}

NSLog(@"Confirming Copy:");

BOOL filecopied = [fileManager fileExistsAtPath:giveCachePath];

if (filecopied) {
    NSLog(@"Give Cache Plist File ready.");
}
else {
    NSLog(@"Cache plist not working.");
}
于 2010-05-18T10:33:17.510 回答