NSFetchedResultsController自定义排序未被调用

Mat*_*off 8 iphone cocoa-touch core-data objective-c nsfetchedresultscontroller

我目前正在尝试使用NSFetchedResultsController从Core Data填充我的项目中的UITableView.我正在使用带比较器的自定义搜索(虽然我也尝试了一个选择器并遇到了同样的问题):

    if (fetchedResultsController != nil) {
        return fetchedResultsController;
    }

    /*
     Set up the fetched results controller.
    */
    // Create the fetch request for the entity.
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    // Edit the entity name as appropriate.
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Object" inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:entity];

    // Set the batch size to a suitable number.
    [fetchRequest setFetchBatchSize:20];
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"objectName" ascending:YES comparator:^(id s1, id s2) {
            NSLog(@"Comparator");
      //custom compare here with print statement
    }];
    NSLog(@"Sort Descriptor Set");
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Object" inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:entity];
    [fetchRequest setSortDescriptors:sortDescriptors];

    NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"firstLetterOfObject" cacheName:@"Objects"];
    [aFetchedResultsController release];
    [fetchRequest release];
    [sortDescriptor release];
    [sortDescriptors release];
    if (![fetchedResultsController performFetch:&error]) {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    return fetchedResultsController;
Run Code Online (Sandbox Code Playgroud)

当我进入此选项卡时,我已经记录了整个程序,发现NSFetchedResultsController在获取时甚至没有进入比较器块.它改为使用一些默认排序方法对其进行排序.

但是,如果我删除并添加一个带有objectName的Object,则它会输入比较器块并正确对表进行排序.

为什么在更改托管对象模型之前,NSFetchedResultsController不使用比较器进行排序?

注意:我也尝试过关闭缓存,和/或在viewDidLoad:中执行提取,但似乎我提取多少次并不重要,但是什么时候.由于某种原因,它只在对象模型被更改后才使用我的排序.

Don*_*Don 8

有几件事我能想到.首先,尽管这可能不是您的问题,但您无法对瞬态属性进行排序.但更可能的是,当在由SQL存储支持的模型中进行排序时,比较器被"编译"为SQL查询,而不是所有的Objective-C函数都可用.在这种情况下,您需要在执行提取后在内存中进行排序.

编辑:请参阅此文档,特别是Fetch Predicates和Sort Descriptors部分.

  • 只是一个猜测,但我认为比较器块在对象模型被更改后工作,因为图形已经在内存中.但这只是猜测.我相信,你手动排序的方法是继承NSArrayController,因此你将失去NSFetchedResultsController的好处.但是,正如您所说,根本问题是您想要将数字排序到底部.在我的头脑中,我会说在你的对象上创建一个排序顺序属性并使用它,但我没有使用排序描述符做足够的自定义排序. (2认同)