iphone - NSFetchedResultsController 自定义排序未被调用

标签 iphone objective-c cocoa-touch core-data nsfetchedresultscontroller

我目前正在尝试使用 NSFetchedResultsController 从核心数据中填充我的项目中的 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;

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

但是,如果我删除并添加一个带有 objectName 的对象,它就会进入比较器 block 并正确地对表进行排序。

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

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

最佳答案

我能想到一些事情。首先,虽然这可能不是您的问题,但您不能对 transient 属性进行排序。但更有可能的是,当在 SQL 存储支持的模型中进行排序时,比较器被“编译”为 SQL 查询,并且并非所有 Objective-C 函数都可用。在这种情况下,您需要在执行提取后在内存中进行排序。

编辑:看这个doc ,特别是获取谓词和排序描述符部分。

关于iphone - NSFetchedResultsController 自定义排序未被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4789782/

相关文章:

ios - iPhone 复制文件

ios - GCD调试锁定 key 的串行队列值的描述?

iphone - UIApplicationDelegate协议(protocol)中神秘的+initialize方法: Why can't I see it in the documentation?

iphone - 设置 UIWindow 的 rootViewController 有什么作用?

iphone - 如何判断UINavigationControllers中的prior visibleViewController是什么?

iphone - 添加 key 到 NSDictionary (iPhone SDK)

ios - 特定 UITableView 上的新 UITabbar

iPhone 5 View 框架变化

iphone - iPhone 应用程序的 "about"文本内的超链接

ios - 在 map 上点击手势