我有两个数组,一个是来自核心数据(array1)的获取请求的数组,另一个是从 web(array2)中提取的数据。我想做的是将array1与array2进行比较,并且array2中不在array1中的任何项目都需要添加到核心数据中。
我从中提取的数据具有与每个人相关联的 ID。当我创建一个新的“人”实体时,我也会用它来保存这个 ID。我不确定如何使用 Person 的 id 比较数组,甚至不知道如何在数组中访问它。
这是获取请求:
NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
NSError *error = nil;
[fetch setEntity:[NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.managedObjectContext]];
NSSortDescriptor *sorter = [NSSortDescriptor sortDescriptorWithKey:@"Pid" ascending:YES];
request.sortDescriptors = @[sorter];
NSArray *items = [self.managedObjectContext executeFetchRequest:request error:&error];
我以与对新数据排序的 array2 相同的方式对 fetch 进行排序。我只是不确定如何比较两者,然后将新项目添加到核心数据中。请帮忙?
更新:
NSDictionary *qDict = [JSON objectForKey:@"person"];
NSArray *qArry = [JSON objectForKey:@"person"];
//Used to print the id's
_testArray = [NSMutableArray arrayWithArray:[qDict valueForKey:@"id"]];
for (NSNumber *numb in _testArray) {
NSLog(@"id = %@", numb);
}
NSError *error = nil;
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"Pid IN %@", [qDict valueForKey:@"Pid"]];
[fetchRequest setPredicate:predicate];
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"Pid" ascending:YES]]];
NSArray *items = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
NSLog(@"%d how many items from the fetch", items.count);
for (NSDictionary *qdt in qArry) {
NSUInteger currentIndex = 0;
Person *q = nil;
if ([items count] > currentIndex) {
q = [items objectAtIndex:currentIndex];
}
if ([q.Pid integerValue] == [[qdt objectForKey:@"id"] integerValue]) {
// Either update the object or just move on
}
else {
// Add the object to core data
q = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.managedObjectContext];
q.url = [qdt valueForKey:@"url"];
q.Pid = [qdt objectForKey:@"id"];
q.text = [qdt valueForKey:@"personText"];
NSError *error = nil;
[_managedObjectContext save:&error];
}
currentIndex++;
}
//[_managedObjectContext save:&error];
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Error retrieving data" message:@"Please try again" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[av show];
}];