首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NSSortDescriptor忽略计算器块

问NSSortDescriptor忽略计算器块
EN

Stack Overflow用户
提问于 2012-06-14 03:49:49
回答 1查看 1.8K关注 0票数 4

我有一个核心数据类"Meeting“,它有一个属性"date”,我希望使用NSFetchedResultsController将其显示在TableView中。会议应该以两种方式排序:首先,一个月的所有会议都应该总结在同一部分中,一个月/部分中的所有会议都应该按日期排序。

代码语言:javascript
复制
    NSComparisonResult (^periodSortBlock)(id, id) = ^(id obj1, id obj2) {                
        NSLog(@"Debug");            

        NSDate *date1 = (NSDate *)obj1;
        NSDate *date2 = (NSDate *)obj2;

        // Pseudocode
        Month *month = [Month monthWithDate:date1];
        NSComparisonResult result = NSOrderedSame;

        if ([Month date:date2 afterDate:month.end])
            result = NSOrderedAscending;
        else if ([Month date:date2 beforeDate:month.start])
            result = NSOrderedDescending;

        return result;
    };        

    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Meeting"];        
    fetchRequest.predicate = [NSPredicate predicateWithFormat:@"SELF IN %@", self.meetings];

    NSSortDescriptor *sectionByMonth = [NSSortDescriptor sortDescriptorWithKey:@"date" ascending:false comparator:periodSortBlock];
    NSSortDescriptor *sortByDate = [NSSortDescriptor sortDescriptorWithKey:@"date" ascending:false];

    fetchRequest.sortDescriptors = [NSArray arrayWithObjects:sectionByMonth, sortByDate, nil];

    frc = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"date" cacheName:nil];
    [frc performFetch:nil];

代码编译时没有任何错误,但排序并不像预期的那样工作:每个会议都有自己的部分。

就我所见,排序块被完全忽略且不被调用: NSLog语句不会产生任何输出,块中的断点也不会停止执行。

我可以使用sortDescriptorWithKey:ascending:,而不是sortDescriptorWithKey:ascending:comparator:。结果是完全相同的。

如果块直接在sortDescriptorWithKey:ascending:comparator:语句中声明,或者声明为变量(类似于上面),也不会有任何区别。

将块定义为(NSDate*,NSDate*)而不是(id,id)也没有区别。

这里出了什么问题?我可以理解块内的排序是否会产生一些错误。但是它怎么可能不调用这个块呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-06-14 18:23:31

多亏了Paul的提示,我才能找出问题所在。可以在Apple docs中找到解决方案(查看"Fetch Predicates and Sort Descriptors“部分)。

我以为NSFetchRequest只会使用SQL从SQLite DB获取对象,然后使用SortDiscriptors对内存中获取的对象进行排序。事实并非如此:似乎整个排序工作也交给了SQLite商店。当然,来自该块的Obective-C状态不能转换为SQL查询,因此该块被忽略。

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11022287

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档