我想读/写cache.plist
如果我想阅读存储在资源文件夹中的现有预制plist文件,我可以去:
path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathWithComponent@"cache.plist"];
NSMutableDictionary *root = ...
但我希望从iPhone上读到它。
不能,Resources文件夹只能读取。
所以我需要使用:
NSDocumentDirectory, NSUserDomain,YES
那么如何将我的plist文件预先安装到文档目录位置?
因此意味着我不必乱用在启动时复制plist文件的不整洁代码。 (除非这是唯一的方法)。
答案 0 :(得分: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 - 真的不是太乱了吗?
答案 1 :(得分:1)
易。首先查看它是否在文档目录中。如果不是,请在应用程序的Resources文件夹([[NSBundle mainBundle] pathForResource...]
)中找到它,然后使用[[NSFileManager defaultManager] copyItemAtPath:...]
将其复制到文档目录中。然后使用文档目录中的新副本而不受惩罚。
答案 2 :(得分: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.");
}