簡體   English   中英

按月將NSArray與NSDate對象分類到NSDictionary中

[英]Sort NSArray with NSDate object into NSDictionary by month

我正在構建一個UITableView並希望按月分組,以便我可以將這些字符串作為我的節標題,例如:

February 2013
- Item 1
- Item 2

January 2013
- Item 1
- Item 2

我有一個NSArray ,它有自定義對象,其pubDate屬性是NSDate

如何使用該NSDate對象按月將自定義對象分組為NSDictionary

像這樣排序數組

NSArray *sortedArray = [yourArrayOfCustomObjects sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        NSDate *firstDate = [(YourCustomObject*)obj1 pubDate];
        NSDate *secondDate = [(YourCustomObject*)obj2 pubDate];
        return [firstDate compare:secondDate];        

    }];

//現在進行簡單的迭代,您可以確定所有相同月份的條目。

//代碼不完整僅用於說明目的。

//您還必須處理年度變化。

int curMonth = 0;
int prevMonth = 0;
foreach(CustomObject *obj in sortedArray)
{
   NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:obj.pubDate];
   prevMonth = curMonth; 
   curMonth = components.month;
   if(prevMonth != 0 && curMonth != prevMonth)
   {
      //Month Changed
   }
}

看看NSDateComponents 如果您將日期轉換為日期組件:

[[NSCalendar currentCalendar] components:(NSMonthCalendarUnit | NSYearCalendarUnit) fromDate:date]

然后你會有對象,你可以很容易地比較平等。

我想,這個問題沒有得到Ole Begemann的答案,但這是一個鏈接(我無法發表評論<repo)我正在回答這個問題,

如果有人仍在尋找一些優雅的解決方案,請檢查一下,

http://oleb.net/blog/2011/12/tutorial-how-to-sort-and-group-uitableview-by-date/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM