【问题标题】:custom sections based on current date for nsfectedresultscontrollernsfetchedresultscontroller 基于当前日期的自定义部分
【发布时间】:2011-10-20 04:23:58
【问题描述】:

我想将三个部分用于 tableview:

新问题 = 在此日期报告的问题,无论状态如何。 活跃问题 = 在此日期之前报告的问题仍需要跟进。 已关闭的问题 = 在此日期之前报告的问题,不需要跟进。

我有一个瞬态属性可以正确报告这些部分 - 分别为 0、1、2。

我已经尝试了多种方法来让我的 NSFetchedResultsController 正确排序结果以供 tableview 显示。我发现您无法对 NSFetchedResultsController 中的瞬态属性进行排序,因此我尝试像这样进行排序:

     //create sort keys
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateStyle:NSDateFormatterShortStyle];
[df setTimeStyle:NSDateFormatterNoStyle];
NSString *nowString = [df stringFromDate:[NSDate date]];
NSDate *todayDateWithoutTime = [df dateFromString:nowString];
[df release];
NSSortDescriptor *sortIsNew = [[NSSortDescriptor alloc] initWithKey:@"dateReported" ascending:YES comparator:^(id obj1,id obj2){
    NSDate *date1 = obj1;
    NSDate *date2 = obj2;
    NSComparisonResult comparisonResult;
    if ([date1 timeIntervalSinceDate:todayDateWithoutTime] == 0) {
        if ([date2 timeIntervalSinceDate:todayDateWithoutTime] == 0) {
            comparisonResult = NSOrderedSame;
        } else {
            comparisonResult = NSOrderedAscending;
        }
    } else {
        if ([date2 timeIntervalSinceDate:todayDateWithoutTime] == 0) {
            comparisonResult =  NSOrderedDescending;
        } else {
            comparisonResult = NSOrderedSame;
        }
    }
    return comparisonResult;
}];
NSSortDescriptor *sortByFollowUp = [[NSSortDescriptor alloc] initWithKey:@"requiresFollowUp" ascending:NO];
NSSortDescriptor *sortByReportDate = [[NSSortDescriptor alloc] initWithKey:@"dateReported" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortIsNew, sortByFollowUp,sortByReportDate, nil];
[fetchRequest setSortDescriptors:sortDescriptors];

不太确定我对块的使用是否正确,但无论如何,据我所知,它永远不会被调用。我在那里放了一些日志语句,它们没有报告。显然“sortByFollowUp”和“sortByReportDate”描述符按预期工作,但不是“sortIsNew”。如果没有新问题,一切正常。在第一部分有新问题的任何情况下,应用程序都会崩溃,因为排序与这些部分不匹配。

我知道我可以通过直接获取请求和数组非常轻松地做到这一点。使用 fetched results 控制器似乎是正确的,以避免在大多数问题不需要时将整个问题表拉入内存,并且在任何给定时刻只会显示少数问题。当您想要自定义部分时,它真的很难使用吗?

【问题讨论】:

  • 我已经通过向我的问题实体添加一个新问题字段来解决这个问题。这是一个可怕的组合,因为现在我必须在每一个可能的情况下追逐日期可能会更改并更新该属性。如果它们不匹配,它肯定会爆炸。一定有更好的办法。

标签: objective-c core-data nsfetchedresultscontroller objective-c-blocks comparator


【解决方案1】:

由于我没有收到任何答案,我以我自己的结论结束这个问题。 将瞬态值保存为属性实际上似乎是最简单的解决方法。我已经尝试过组合 NSFetchedResultsController 和自定义数组方法的变体,但看起来你失去了 NSFetchedResultsController 的很多好处。您最终不得不追踪所有接收到的事件并根据需要刷新数组。在这种情况下,您似乎还不如跳过 NSFetchedResultsController 直接处理对象数组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-21
    • 1970-01-01
    • 2011-01-29
    • 2010-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多