如何在 iOS 上将 plist 从bundle移动到文档文件夹



所以我想知道的只是如何在应用程序第一次运行时将 plist 从捆绑包移动到文档文件夹,因为我需要它。拜托,我不知道该怎么做,所以帮帮我。

如果你的名单名字是"朋友"

只需使用以下代码(它将找到文件是否存在并复制)

NSFileManager *fileManger=[NSFileManager defaultManager];
NSError *error;
NSArray *pathsArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *doumentDirectoryPath=[pathsArray objectAtIndex:0];
NSString *destinationPath= [doumentDirectoryPath stringByAppendingPathComponent:@"friends.plist"];
NSLog(@"plist path %@",destinationPath);    
if ([fileManger fileExistsAtPath:destinationPath]){
    //NSLog(@"database localtion %@",destinationPath);
    return;
}
NSString *sourcePath=[[[NSBundle mainBundle] resourcePath]stringByAppendingPathComponent:@"friends.plist:];
[fileManger copyItemAtPath:sourcePath toPath:destinationPath error:&error];

将 plist 从资源复制到文档目录

这个函数应该可以解决问题。

- (void)copyPlist {
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"myplist" ofType:@"plist"];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    [[NSFileManager defaultManager] copyItemAtPath:plistPath toPath:documentsDirectory error:nil];
}

不需要在[[NSFileManager defaultManager] copyItemAtPath:plistPath toPath:documentsDirectory error:nil];中使用 NSError 参数,但它可能对调试有用。

只是抬头...这来自 http://samsoff.es/posts/iphone-plist-tutorial"如今,使用JSON比Plists更受欢迎,因为JSON解析器在速度方面已经走了很长一段路。它们现在实际上比二进制列表更快(这很疯狂)。无论如何,拜托,拜托,请不要为您的 API 使用 plists。生成它们既缓慢又不可靠。您应该使用 JSON。句号。

最新更新