我正在尝试关注 steps found here关于比较两个数组,并知道何时创建新对象,但我只是不明白它是如何工作的:
You end up with two sorted arrays—one with the employee IDs passed into the fetch request, and one with the managed objects that matched them. To process them, you walk the sorted lists following these steps:
Get the next ID and Employee. If the ID doesn't match the Employee ID, create a new Employee for that ID.
Get the next Employee: if the IDs match, move to the next ID and Employee.
Regardless of how many IDs you pass in, you only execute a single fetch, and the rest is just walking the result set.
基本上发生的事情是我有一个来自外部源的对象 ID 数组,而客户端系统只有这些 ID 表示的对象的一个子集。我需要弄清楚我已经拥有哪些对象,如果没有,就一个一个地创建它们。
我不明白这是怎么回事。我在将其转换为代码时遇到问题:
for (int i =0;i<ids.count;i++) {
currentId = [ids objectAtIndex:i];
currentObject = [objects objectAtIndex:i];
if(currentObject.id != currentId) {
//create new object
}
//"get the next employee"
//uh what?
nextEmployee = [objects objectAtIndex:i+1]; //?
if(nextEmployee.id == currentId) {
//"move on to the next id"
continue;
}
}
我不明白那会怎样?我错过了什么?
最佳答案
我在查看核心数据编程指南中的相同示例后发现了这个问题。
这是我的解决方案:
关键是你分别走2个数组,一个数组包含Core Data中需要存在的所有employeeId字符串,另一个包含Core Data中已经存在的Employee对象,由employeeId字符串过滤。两个数组都已排序。
假设我们有包含字符串的已排序 employeeIds 数组:
@"10",@"11",@"12",@"15",@"20"
并且我们有一个 matchingEmployees 数组,其中包含 2 个 employeeId 为 10 和 15 的 Employee 对象。
我们需要为员工 ID 为 11,12 和 20 的员工创建新的员工对象,同时可能更新员工 10 和 15 的属性。所以:
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++;
}
关于iphone - 基本数组比较算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11183008/