2012-06-25 44 views
0

我的应用程序就像一本日志。我保留一天发生的事件的证据。基本上,我有一个实体(显示在桌面上)与“日期”属性。保存新事件时,使用[NSDate日期]存储当前日期。我如何组织tableview,这样所有的事件将按日期排序并显示出来?任何提示将不胜感激!TableView日期部分标题

回答

3

您应该使用NSFetchedResultsControllersectionNameKeyPath参数按日期区分结果。

几个例子herehere

你基本上设置要用作sectionNameKeyPath参数使用的属性,这将是这样的:

fetchedResultsController = [[NSFetchedResultsController alloc] 
          initWithFetchRequest:fetchRequest 
          managedObjectContext:managedObjectContext 
           sectionNameKeyPath:@"date" 
             cacheName:nil]; 

那么你的数据源委托代码会是这个样子:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
    return [[fetchedResultsController sections] count]; 
} 

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView { 
    return [fetchedResultsController sectionIndexTitles]; 
} 

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index { 
    return [fetchedResultsController sectionForSectionIndexTitle:title atIndex:index]; 
} 

编辑:为了按日期对项目进行分组,只需要为托管对象创建一个临时属性 - 实质上是从实际日期派生的日期字符串。

这些在你的.h/.M的顶部像往常一样

@property (nonatomic, strong) NSString *sectionTitle; 

@synthesize sectionTitle; 

去现在你已经创建的属性,要覆盖其存取实际设置标题在请求时。

-(NSString *)sectionTitle 
{ 
    [self willAccessValueForKey:@"date"]; 
    NSString *temp = sectionTitle; 
    [self didAccessValueForKey:@"date"]; 

    if(!temp) 
    { 
     NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
     [formatter setDateFormat:@"d MMMM yyyy"]; // format your section titles however you want 
     temp = [formatter stringFromDate:date]; 
     sectionTitle = temp; 
    } 
    return temp; 
} 

请注意,此代码实际上会检查sectionTitle是否已被缓存,并且只是重新使用它而不重新创建它。如果您期待或允许过去对象的日期发生变化,那么sectionTitle也需要更新,如果情况如此,您还需要为日期本身覆盖mutator,并添加一行以清除它sectionTitle(这样下一次标题被请求时,它将被重新创建)。

- (void)setDate:(NSDate *)newDate { 

    // If the date changes, the cached section identifier becomes invalid. 
    [self willChangeValueForKey:@"date"]; 
    [self setPrimitiveTimeStamp:newDate]; 
    [self didChangeValueForKey:@"date"]; 

    [self setSectionTitle:nil]; 
} 

最后,你应该只是改变了sectionNameKeyPathfetchedResultsController@"sectionTitle"

苹果有一个sample project你可以看看,如果你想看到类似的行动。

+0

谢谢。现在我被困在每个对象的部分,而不是分组 – PonyLand

+0

哦,对了!这是因为它使用的是包含实际小时数/分钟/秒而不是仅仅一天的整个日期对象。我将代码添加到我的答案的底部。 – Dima

+1

解决了:)非常感谢你lolcat!希望这会对像我这样的未来新手有所帮助 – PonyLand