我有一个DiaryEntry对象的NSArray,其中每个DiaryEntry都有一个NSDate date_字段。

我想在表格视图中显示所有DiaryEntry,按星期几分组,
其中每个组按日期升序排列。

因此,我需要使用NSArray,并转换为NSDictionary数组,其中键是星期几(NSDate),值是DiaryEntrys的NSArray,由date_字段按升序排序。

我认为这是一个非常常见的操作,但是在任何地方都找不到任何示例代码。

任何帮助是极大的赞赏。

谢谢!!

最佳答案

以下应该工作(没有实际编译和测试代码)

            NSEnumerator* enumerator;
            DiaryEntrys* currEntry;
            NSMutableDictionary* result;

            /*
             use sorting code from other answer, if you don't sort, the result will still contain arrays for each day of the week but arrays will not be sorted
             */
            [myArray sortUsingDescriptors:....];
            /*
             result holds the desired dictionary of arrays
             */
            result=[[NSMutableDictionary alloc] init];
            /*
             iterate throught all entries
             */
            enumerator=[myArray objectEnumerator];
            while (currEntry=[enumerator nextObject])
            {
                NSNumber* currDayOfTheWeekKey;
                NSMutableArray* dayOfTheWeekArray;
                /*
                 convert current entry's day of the week into something that can be used as a key in an dictionary
                 I'm converting into an NSNumber, you can choose to convert to a maningfull string (sunday, monday etc.) if you like
                 I'm assuming date_ is an NSCalendarDate, if not, then you need a method to figure out the day of the week for the partictular date class you're using

                 Note that you should not use NSDate as a key because NSDate indicates a particular date (1/26/2010) and not an abstract "monday"
                 */
                currDayOfTheWeekKey=[NSNumber numberWithInt:[[currEntry valueForKey:@"date_"] dayOfWeek]];
                /*
                 grab the array for day of the week using the key, if exists
                 */
                dayOfTheWeekArray=[result objectForKey:currDayOfTheWeekKey];
                /*
                 if we got nil then this is the first time we encounter a date of this day of the week so
                 we create the array now
                 */
                if (dayOfTheWeekArray==nil)
                {
                    dayOfTheWeekArray=[[NSMutableArray alloc] init];
                    [result setObject:dayOfTheWeekArray forKey:currDayOfTheWeekKey];
                    [dayOfTheWeekArray release];    // retained by the dictionary
                }
                /*
                 once we figured out which day the week array to use, add our entry to it.
                 */
                [dayOfTheWeekArray addObject:currEntry];
            }

10-04 21:44