代码之家  ›  专栏  ›  技术社区  ›  RickiG

读取/写入与应用程序捆绑在一起的plist文件

  •  1
  • RickiG  · 技术社区  · 15 年前

    我正在为我的应用程序构建一个附加组件,用户可以在其中搜索预先填充了.plist文件中数据的列表中的项目。它是一本nsdictionary。如果搜索到的术语不存在,用户可以点击+按钮并添加它,以便下次使用。

    首先,我认为这和使用nsuserdefaults一样简单,但是出现了一些问题。

    要包含这个列表,我必须将它放在包中,但是如果它存在,我就不能向它添加新的键/值对。我只能对位于文档文件夹中的文件执行此操作。

    所以我想我必须打包plist,然后在第一次运行时,我将把它移到documents文件夹并访问它。

    当我需要更新应用程序时,这就打开了问题,我想它会覆盖用户输入的值。

    有没有一种安全、容易理解、正确的方法来实现我描述的功能?

    感谢您的帮助:)

    编辑: * ** * 实际的方法,如Squad和Tomh所建议的那样 * ** * *

    + (NSMutableDictionary*) genericProducts {
    
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
        NSString *documentsDirectory = [documentPaths objectAtIndex:0];
        NSString *documentPlistPath = [documentsDirectory stringByAppendingPathComponent:@"GenericProducts.plist"];
    
        NSString *bundlePath = [[NSBundle mainBundle] bundlePath];  
        NSString *bundlePlistPath = [bundlePath stringByAppendingPathComponent:@"GenericProducts.plist"];
    
    
        if([fileManager fileExistsAtPath:documentPlistPath]){
    
            NSMutableDictionary *documentDict = [NSMutableDictionary dictionaryWithContentsOfFile:documentPlistPath];
            return documentDict;
    
        } else {
    
            NSError *error;
            BOOL success = [fileManager copyItemAtPath:bundlePlistPath toPath:documentPlistPath error:&error];
    
        if (success) {
            NSMutableDictionary *newlySavedDict = [NSMutableDictionary dictionaryWithContentsOfFile:documentPlistPath];
            return newlySavedDict;
        }
    
        return nil;
    }
    

    }

    如果要向列表中添加新产品:

    + (void) addItemToGenericProducts:(NSString*) newProduct {
    
        NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
        NSString *documentsDirectory = [documentPaths objectAtIndex:0];
        NSString *documentPlistPath = [documentsDirectory stringByAppendingPathComponent:@"GenericProducts.plist"];
        NSMutableDictionary *documentDict = [NSMutableDictionary dictionaryWithContentsOfFile:documentPlistPath];
        [documentDict setObject:newProduct forKey:[MD5Checksum cheksum:newProduct]];
    
        [documentDict writeToFile:documentPlistPath atomically:YES];
    

    }

    2 回复  |  直到 14 年前
        1
  •  2
  •   TheSquad    15 年前

    我对我的sqlite数据库也有同样的想法…

    我最终做的正是这样,将捆绑的文件复制到文档中,以便能够对其进行修改。

    我所做的是在每次启动时检查文件是否存在,如果不存在,则复制它。 如果你更新你的应用程序,文档文件夹将不会被触摸,这意味着从以前版本复制的文件仍然存在。

    唯一的问题是,如果您想升级plist,您必须在应用程序中处理它。如果必须这样做,我建议您使用nsuserdefault来检查应用程序以前的版本是否存在…

        2
  •  2
  •   TomH    15 年前

    更新应用程序时,不会更改文档目录的内容。

    当用户删除应用程序时,文档目录的内容将被删除。

    当应用程序第一次运行时,向nsuserdefaults写入一个标志。在应用程序的后续运行中,检查标志是否存在。(或者,您可以检查文档目录中是否存在plist)