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:
<
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++;
}