2013-10-15 75 views
0

我有一个数组,我需要在UITableView中分段显示。根据日期排列创建年份

我目前按照日期顺序显示所有对象下的一个部分,但我需要按年份对它们进行分区,我不确定如何去做。

我的目标是一样的东西......

@interface MyEvent : NSObject 

@property NSDate *date; 
@property NSString *title; 
@property NSString *detail; 

@end 

我的数组是按日期顺序排列,这些对象的数组。

我可以直接从这个数组中做到这一点,还是我需要将数组分成二维数组。

即NSArray的NSArray,其中第二个NSArray中的每个对象都在同一年。

回答

1

这是很容易使用TLIndexPathDataModelTLIndexPathTools为你的数据结构做。基于块的初始化提供了一些方法来将数据组织成部分之一:

NSArray *sortedEvents = ...; // events sorted by date 
TLIndexPathDataModel *dataModel = [[TLIndexPathDataModel alloc] initWithItems:sortedEvents sectionNameBlock:^NSString *(id item) { 
    MyEvent *event = (MyEvent *)item; 
    NSString *year = ...; // calculate section name for the given item from date 
    return year; 
} identifierBlock:nil]; 

,然后将数据源的方法,使用的数据模型API变得非常简单:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    return self.dataModel.numberOfSections; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return [self.dataModel numberOfRowsInSection:section]; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    NSString *cellId = ...; 
    UITableViewCell *cell = ...; // dequeue cell 
    MyEvent *event = [self.dataModel itemAtIndexPath:indexPath]; 
    ... // configure cell 
    return cell; 
} 
相关问题