2012-01-18 66 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