我的plist已更改,如何替换文档目录中更改的字符串

时间:2012-09-09 13:35:22

标签: objective-c ios

我的plist是array with dictionaries

启动时,.plist会从bundle复制到documents directory,如果它已经存在的话。

但是如果plist已存在于documents directory

必须根据捆绑包中更新的双字典检查每个字典,以查找“区”字符串中的更改。

当然,如果已经进行了更改,请替换字符串。

这是复制plist功能:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[self copyPlist];
return YES;
}

- (void)copyPlist {

NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"Wine.plist"];
NSString *bundle = [[NSBundle mainBundle] pathForResource:@"Wine" ofType:@"plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];

if (![fileManager fileExistsAtPath: path]) {
    [fileManager copyItemAtPath:bundle toPath:path error:&error];
} else {
//I need to check if the "District" value has been changed in any of the dictionaries.
}
}

有关如何做到这一点的任何建议,或有用的教程/示例代码?

我的猜测是我必须将plist的内容提取到NSMutableArrays中:bundleArraydocumentsArray。然后在数组中找到匹配的字典。可以通过查看“Name”字符串来完成。然后比较匹配词典中的两个“区”字符串并查找任何更改,并替换更改的字符串。但是我不知道应该怎么做,所以任何帮助都非常有用,因为这非常重要!

1 个答案:

答案 0 :(得分:1)

我认为你的词典结构如下: Root为“Array”

  1. 字典1以“区域作为关键之一”

  2. 字典2以“区为一键”

  3. 您可以检查Array的特定索引中的两个 NSDictionary 是否相等,我在下面编码。

    NSArray *bundleArray=[[NSArray alloc] initWithContentsOfFile:@"path to .plist in bundle"];;
    NSArray *documentArray=[[NSArray alloc] initWithContentsOfFile:@"path to .plist in DocumentDirectory"];
    BOOL updateDictionary=NO;
    
    for(int i=0;i<bundleArray.count;i++){
        NSDictionary *bundleDic=[bundleArray objectAtIndex:i];
    
        NSDictionary *documentDic=[documentArray objectAtIndex:i];
    
        if(![bundleDic isEqualToDictionary:documentDic])
        {
            /*
             *if there is any change between two dictionaries. 
             * i.e bundle .plist has changed so update .plist in document Directory
             */
    
            [documentDic setValue:[bundleDic objectForKey:@"District"] forKey:@"District"];
            updateDictionary=YES;
    
        }
    }
    
    //Update Dictionary
    if(updateDictionary){
        [documentArray writeToFile:@"path to .plist in DocumentDirectory" atomically:YES];
    }