2010-05-18 88 views
0

我想读/写cache.plist的plist鸡/蛋的情况

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

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

但随后我希望从iPhone读取它。

不能,资源文件夹只能读取。

所以我需要使用:

NSDocumentDirectory, NSUserDomain,YES 

所以,我怎么能有我的plist文件预装到文档目录的位置?

因此,我不必在启动时复制plist文件的不整齐代码。 (除非这是唯一的方法)。

回答

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."); 
} 
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

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

+0

普里莫,我觉得两个答案都或多或少我想听到的声音,有种给我一个全面的检查。 谢谢Dave deLong和alku83 – 2010-05-18 07:25:43