如何从Another Array更新一个数组

时间:2014-03-06 14:06:02

标签: ios iphone arrays

这是我在Document Dir中保存的旧数组1,数组2是从服务器获取的。在这里,我必须在从带有阵列2的服务器获取数据后更新阵列1的相应数据。

enter image description here

更新阵列1之后将是:

enter image description here

2 个答案:

答案 0 :(得分:0)

您无法写入捆绑包中的plist。如果您需要plist可编辑,则需要在文档目录中创建自己的plist并使用该plist。

流速:

  1. 首次启动您的应用时,从捆绑包中获取plist并创建一个保存在Documents目录中的新plist,其中包含原始plist中的内容。

  2. 每当您需要plist中的数据时,请使用您在启动时创建的数据并将其存储在Documents目录中。切勿再次使用捆绑包中的那个。

  3. 当您需要更新plist时,请更新您在Documents中存储的那个。

答案 1 :(得分:0)

以下是如何比较两个阵列并更新本地阵列的示例。请记住,此代码可能已经过优化,但至少应该让您了解如何执行此操作: - )

- (NSArray *)updateArray:(NSArray *)currentArray withData:(NSArray *)webServerData {
    NSMutableArray *arr = [[NSMutableArray alloc] init];

    //Loop through each NSDictionary in the local array
    for (NSDictionary *dict in currentArray) {
        NSString *name = [dict objectForKey:@"NAME"];
        BOOL updateDict = NO;

        //For each NSDictionary, loop through the NSDictionaries in the array from the web server
        for (NSDictionary *dict2 in webServerData) {

            //If the name in the local dict is the same as the one in the one from the web server, check if the age is different
            if ([name isEqualToString:[dict2 objectForKey:@"NAME"]]) {
                if ([[dict objectForKey:@"AGE"] integerValue] != [[dict2 objectForKey:@"AGE"] integerValue]) {

                    //If the age is different, add the new dictionary
                    [arr addObject:dict2];
                    updateDict = YES;
                }

                break;
            }
        }

        //Add the dict from local array if no new data was found in the web server array
        if (!updateDict) {
            [arr addObject:dict];
        }
    }

    return [arr copy];
}