我有NSPredicate
在NSArray
个ID内搜索id,
('id in %@',array)
有没有办法让该获取的结果集按照相同的数组顺序排序?
我现在的代码是
+(NSArray*) findIn:(NSArray*)identifiers{
if(identifiers == nil) return nil;
NSPredicate *searchFilter = [NSPredicate predicateWithFormat:@"id IN %@", identifiers];
NSArray *fetchedObjects = [GSBaseModel setupFetch:[[self class] managedObjectEntityName] andFilter:searchFilter andSortKey:nil];
if([fetchedObjects count] == 0){
return nil;
}
return fetchedObjects;
}
setupfecth只执行以下操作:
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:[NSManagedObjectContext MR_defaultContext]];
[fetchRequest setEntity:entity];
return = [[NSManagedObjectContext MR_defaultContext] executeFetchRequest:fetchRequest error:&error];
答案 0 :(得分:1)
如果你想获取核心数据对象并用id数组链接它们,你应该考虑使用功能强大的NSDictionary:
因此,一旦获取了所有对象,只需将这些对象存储在由id:
键入的字典中NSDictionary *managedObjectsKeyedByID = [NSDictionary dictionaryWithObjects:fetchedObjects forKeys:[fetchedObjects valueForKey:@"identifier"]];
现在,您可以遍历数组并使用字典检查匹配项:
for (NSString *identifier in arrayOfServerIDs) {
NSManagedObject *existingObject = managedObjectsKeyedByID[identifier];
if(!existingObject) {
//insert a new one
} else {
//update
}
}
答案 1 :(得分:0)
我终于以这种方式推了它
感谢Sort NSArray of custom objects based on sorting of another NSArray of strings
+(NSArray*)sortWithArray:(NSArray*)toSort sorted:(NSArray*)sortedIdentifiers{
NSMutableArray *sorted = [NSMutableArray array];
// pre-populate with objects
for (int i = 0; i < sortedIdentifiers.count; i++)
{
[sorted addObject:[NSNull null]];
}
// place the items at the correct position
for (NSManagedObject *a in toSort)
{
NSNumber* identifier = [a valueForKey:@"id"];
NSUInteger idx = [sortedIdentifiers indexOfObject:[identifier stringValue]];
if (idx != NSNotFound)
{
[sorted setObject:a atIndexedSubscript:idx];
}
}
// finally remove all the unecesarry placeholders if one array was smaller
[sorted removeObject:[NSNull null]];
return sorted;
}