2012-01-18 63 views
0

以下是我想按月订购的UITableView的屏幕截图。目前,他们按字母顺序排列了小标题的第一个字母,我应该使用什么代码将事件排序为几个月? (顺便说一句我已经摸索出如何订购部分)根据部分订购对象

Image to be ordered

赞赏任何帮助,

勒布

回答

1

最好的解决方案取决于您的数据模型是什么样子。假设您的数据模型不会非常频繁地更改,可能最简单也最有效的方法是按照您想要的顺序(基于每个项目的日期)对每个部分的数据进行排序。创建一个指针列表(或索引,同样取决于你的数据结构的细节),那么你所要做的就是在该部分的排序索引结构中查找行索引并在cellForRowAtIndexPath中显示该元素的数据。要优化,您可以在数据结构中保留一个布尔“已排序”字段,该字段在表中数据发生变化时设置为false,然后仅在cellForRowAtIndexPath中按需排序并将“sorted”设置为true。

编辑:请求一步一步的详细说明

OK,这里是我如何会去一下,假设每个部分的更详细一点的储存无序像NSMutableArray的一个排序的容器。再次,最好的解决方案取决于应用程序的细节,例如条目条目更新的频率和组织数据的频率,以及条目数量的上限等。这与我原来的建议略有不同因为该部分的数据容器是直接排序的,并且不使用外部排序索引。

添加的NSMutableSet sortedSections成员方便的地方,靠近你的数据模型(里面,如果你在一个类中定义它的类将是最好的)

// a section number is sorted if and only if its number is in the set 
NSMutableSet *sortedSections; 

当部分条目被改变,添加或删除,标志着该部分从集中删除其数量

// just added, deleted, or changed a section entry entry 
unsigned int sectionNum; // this section changed 
... 
NSNumber *nsNum = [NSNumber numberWithUnsignedInt:sectionNum]; 
[obj.sortedSections removeObject:nsNum]; 

在作为未分类的cellForRowAtIndexPath(这可能不是本次检查中最优化的地方,但它是一个快速检查,是让最简单的位置排序工作),检查如果该部分被排序。

unsigned int sectionNum = [indexPath section]; 
NSNumber *nsNum = [NSNumber numberWithUnsignedInt:sectionNum]; 
if ([obj.sortedSections containsObject:nsNum]) 
    // already sorted, nothing to do 
else 
{ 
    // section needs to be resorted and reloaded 
    [mySectionData sortUsingFunction:compareSectionEntriesByDate context:nil]; 
    // mark the section as sorted now 
    [obj.sortedSections addObject:nsNum]; 
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationNone]; 
} 

下面是一个例子排序功能,假设您的输入结构类型的NSDictionary和您存储的日期作为NSDate的用钥匙不变kEntryNSDate(你将自己定义)

// sort compare function for two section entries based on date 
// 

static int compareSectionEntriesByDate(id e1, id e2, void *context) 
{ 
    NSDictionary *eDict1 = (NSDictionary *) e1; 
    NSDictionary *eDict2 = (NSDictionary *) e2; 
    NSDate *date1 = [eDict1 objectForKey:kEntryNSDate]; 
    NSDate *date2 = [eDict2 objectForKey:kEntryNSDate]; 

    int rv = [date1 compare:date2]; 
    return rv; 
} 

对象这应该足够详细,让你走,祝你好运!

+0

谢谢SOOOO多! – 2012-01-19 11:07:58