Basic array comparison algorithm

后端 未结 4 1590
半阙折子戏
半阙折子戏 2021-01-07 08:44

I\'m trying to follow the steps found here on comparing two arrays, and knowing when to create a new object, but I just don\'t understand how it works:

<
4条回答
  •  温柔的废话
    2021-01-07 09:46

    I found this question after looking at the same example in the Core Data Programming Guide.

    This is my solution:

    The key is that you are walking 2 arrays separately, one array contains all the employeeId strings that need to exist in Core Data, and the other contains Employee objects that already exist in Core Data, filtered by the employeeId strings. Both arrays have been sorted.

    So lets say we have the sorted employeeIds array containing strings:

    @"10",@"11",@"12",@"15",@"20"
    

    And that we have a matchingEmployees array containing 2 Employee objects with employeeId 10 and 15.

    We need to create new Employee objects for employees with employeeIDs 11,12 and 20, while potentially updating the attributes of employees 10 and 15 . So:

    int i = 0; // employeeIds array index
    int j = 0; // matchingEmployees array index
    
    while ((i < [employeeIds count]) && (j <= [matchingEmployees count])){
    
      NSString *employeeId = [employeeIds objectAtIndex:i];
    
      Employee *employee = nil;
    
      if ([matchingEmployees count]!=0)
          employee = [matchingEmployees objectAtIndex:j];
    
      if (![employeeId isEqualToString:employee.employeeId]){
    
          employee = //Insert new Employee entity into context
          employee.employeeId = employeeId;
    
          //Set any attributes for employee that do not change
      }
      else {
          //We matched employeeId to Employee so the next iteration
          //of this loop should check the next Employee object
          j++; 
      }
    
      //Set any attributes for employee that change with each update
    
      i++;
    }
    

提交回复
热议问题