NSFetchedResultsController不对初始提取进行排序

时间:2012-05-25 15:59:19

标签: objective-c ios core-data nsfetchedresultscontroller magicalrecord

我遇到NSFetchedResultsController的核心数据问题。我在父实体和子实体之间有一对多的关系。 childFetchedResults.fetchedObjects属性中的数组未按number排序(数字是模型中的int32属性)。如果我使用MagicalRecord便利类别方法似乎并不重要。

NSFetchRequest *req = [Child MR_requestAllSortedBy:@"number" ascending:YES withPredicate:[NSPredicate predicateWithFormat:@"parent = %@", self.parent]];
childFetchedResults = [[NSFetchedResultsController alloc] initWithFetchRequest:req managedObjectContext:[NSManagedObjectContext MR_defaultContext] sectionNameKeyPath:nil cacheName:nil];
childFetchedResults.delegate = self;
NSError *error;
[childFetchedResults performFetch:&error];
NSLog(@"fetched objects: %@", childFetchedResults.fetchedObjects);

但是,如果我使用完全相同的排序描述符对获取的对象数组进行排序,它可以正常工作:

NSLog(@"fetched objects: %@", [childFetchedResults.fetchedObjects sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"number" ascending:YES]]]);

我认为,在为获取请求指定排序描述符时,只能使用Core Data可以传递给SQLite存储的比较器。但我认为在这种情况下这应该不重要,因为SQLite必须支持按数字排序。

有人解决了这个问题吗?我觉得这与此处描述的问题类似:NSSortDescriptor not being called

至于MR_requestAllSortedBy,它位于MagicalRecord,这是实现:

+ (NSFetchRequest *) MR_requestAllSortedBy:(NSString *)sortTerm ascending:(BOOL)ascending inContext:(NSManagedObjectContext *)context
{
    NSFetchRequest *request = [self MR_requestAllInContext:context];

    NSSortDescriptor *sortBy = [[NSSortDescriptor alloc] initWithKey:sortTerm ascending:ascending];
    [request setSortDescriptors:[NSArray arrayWithObject:sortBy]];

    return request;
}

2 个答案:

答案 0 :(得分:2)

所以这是因为使用未保存的更改来获取嵌套的MOC。在执行提取之前,使用父MOC提取或保存嵌套的MOC可以解决问题。与此问题中的内容类似:NSSortdescriptor ineffective on fetch result from NSManagedContext

答案 1 :(得分:0)

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"RemainderDataBase" inManagedObjectContext:[self managedObjectContext]];
    NSSortDescriptor *nameSort = [[NSSortDescriptor alloc]initWithKey:@"title" ascending:YES];
    NSArray *sortDescriptor = [[NSArray alloc]initWithObjects:nameSort, nil];
    fetchRequest.sortDescriptors = sortDescriptor;
    NSPredicate *p1=[NSPredicate predicateWithFormat:@"startdate > %@", [NSDate date]];
    [fetchRequest setPredicate:p1];
    [fetchRequest setEntity:entity];

我认为您正在寻找上述代码..