我想读/写cache.plist
如果我想读取存储在resources文件夹中的现有预制plist文件,我可以转到:
path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathWithComponent@"cache.plist"];
NSMutableDictionary *root = ...但是,我希望从iPhone中读取它。
不能,资源文件夹是只读的。
所以我需要使用:
NSDocumentDirectory, NSUserDomain,YES那么,如何才能将plist文件预装到文档目录位置?
因此,这意味着我不必纠结于在启动时复制plist文件的杂乱代码。(除非这是唯一的方法)。
发布于 2010-05-18 18:33:18
最终产品
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-18 14:45:43
我知道这不是你真正想要的,但据我所知,将文档放入Documents文件夹的唯一方法是仅在第一次启动时才实际复制它there...but。我将对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-18 14:46:00
很简单。首先查看它是否在文档目录中。如果不是,请在应用程序的Resources文件夹([[NSBundle mainBundle] pathForResource...])中找到它,然后使用[[NSFileManager defaultManager] copyItemAtPath:...]将其复制到documents目录中。然后使用文档目录中的新副本而不受惩罚。
https://stackoverflow.com/questions/2854997
复制相似问题