本文介绍了用数组的顺序在子句中对NSPredicate进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 NSPredicate
,它在 NSArray
的ids,
某物内搜索id像
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?
我现在拥有的代码是
+(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会执行以下操作:
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];
推荐答案
我终于这样解决了
感谢
+(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;
}
这篇关于用数组的顺序在子句中对NSPredicate进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!