问题
I have a NSPredicate
that does a search of id within an NSArray
of ids,
something like
('id in %@',array)
Is there a way to get the resultset of that fetch sorted with the same array's order?
The code I have now is
+(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;
}
The setupfecth just does the following:
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];
回答1:
I finally soved it this way
Thanks to 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;
}
回答2:
If you want to fetch core data objects and link them up with an array of id's you should consider using the ever so powerful NSDictionary:
So once you have fetched all your objects simply store those objects in a dictionary keyed by id:
NSDictionary *managedObjectsKeyedByID = [NSDictionary dictionaryWithObjects:fetchedObjects forKeys:[fetchedObjects valueForKey:@"identifier"]];
Now you can iterate over your array and check for matches using your dictionary:
for (NSString *identifier in arrayOfServerIDs) {
NSManagedObject *existingObject = managedObjectsKeyedByID[identifier];
if(!existingObject) {
//insert a new one
} else {
//update
}
}
来源:https://stackoverflow.com/questions/26989573/sort-nspredicate-with-in-clausule-with-arrays-order