Objective C - 将对象数组(带有日期字段)转换为数组字典(按星期几键控)

发布于 2024-08-19 14:05:39 字数 305 浏览 5 评论 0原文

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

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

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

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

非常感谢任何帮助。

谢谢!!

I have an NSArray of DiaryEntry objects, where each DiaryEntry has an NSDate date_ field.

I want to display all of the DiaryEntrys in a table view, grouped by the day of the week,
where each group is sorted by date in ascending order.

So, I need to take the NSArray, and convert to an NSDictionary of arrays, where the key is the day of the week (NSDate), and the value is an NSArray of DiaryEntrys, ordered by the date_ field in ascending order.

I figure this is a pretty common operation, but can't find any sample code anywhere.

Any help is greatly appreciated.

Thanks!!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

游魂 2024-08-26 14:05:40

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

            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];
            }

The following should work (did not actually compile and test the code)

            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];
            }
悲念泪 2024-08-26 14:05:40

好吧,我假设您的 DiaryEntry 有一个日期属性。这是一个快速但肮脏的版本,你可以让它变得更好。

NSMutableDictionary *map = [[[NSMutableDictionary alloc] init] autorelease];
NSMutableArray *array;
for (DiaryEntry *entry in myArray) {
    array = [map objectForKey:entry.date];
    if (!array) {
        array = [[[NSMutableArray alloc] init] autorelease];
        [map setObject:array forKey:entry.date];
    }
    [array addObject:entry];
}

我会仔细检查代码中的方法名称/编译...我有点即兴发挥,但它基本上是:

浏览列表。对于找到的每个条目,查看是否有与该日期关联的数组。如果没有,请创建它。添加到该数组。

注意 您可能要考虑将结构更改为数组...除非您居住在超过 7 天的土地上,否则您可以存储按特定顺序存储的数组。我尝试尽可能避免地图结构,除非我有大量对象并且我想要快速查找。

Well, I assume your DiaryEntry has a date property. Here's a quick and dirty version, you could make this a lot nicer.

NSMutableDictionary *map = [[[NSMutableDictionary alloc] init] autorelease];
NSMutableArray *array;
for (DiaryEntry *entry in myArray) {
    array = [map objectForKey:entry.date];
    if (!array) {
        array = [[[NSMutableArray alloc] init] autorelease];
        [map setObject:array forKey:entry.date];
    }
    [array addObject:entry];
}

I'd double check the code for method names/compilation... I'm sort of winging it here however it's basically:

Go through the list. For each entry you find, see if there's an array associated with that date. If not, create it. Add to that array.

Note You may want to consider changing the structure to an array... unless you live in a land with more than 7 days, you can store an array stored in a particular order. I try to avoid map structures as much as possible unless I have a ton of objects and I want the quick lookup.

深巷少女 2024-08-26 14:05:40

我没有测试它,但我可以编写这段代码,您可以根据需要进行改进。


// Ordering the array ascending
            myArray = [myArray sortedArrayUsingDescriptors:
                                [NSArray arrayWithObject: 
                                 [[[NSSortDescriptor alloc] initWithKey:@"date_ field"
                                                              ascending:YES
                                                               selector:@selector(compare:)] autorelease]]];

            NSMutableDictionary *myDictionary = [[NSMutableDictionary alloc] init];
            NSMutableArray *arrayForCurrentDate = [[NSMutableArray alloc] init];
            NSString *lastDate = [myArray objectAtIndex:0];
            for (int i=0; i< [myArray count]; i++)
            {
                if (![lastDate isEqualToString:[myArray objectAtIndex:i])
                {
                    if ([arrayForCurrentDate count])
                        [myDictionary setObject:arrayForCurrentDate forKey:lastDate];
                    [arrayForCurrentDate removeAllObjects];
                    lastDate [myArray objectAtIndex:i];
                }
                [arrayForCurrentDate addObject:];
            }
            if ([arrayForCurrentDate count])
                  [myDictionary setObject:arrayForCurrentDate forKey:lastDate];

干杯,
虚拟网络

I didn't test it, but I could wrote this piece of code that you can improve as you need.


// Ordering the array ascending
            myArray = [myArray sortedArrayUsingDescriptors:
                                [NSArray arrayWithObject: 
                                 [[[NSSortDescriptor alloc] initWithKey:@"date_ field"
                                                              ascending:YES
                                                               selector:@selector(compare:)] autorelease]]];

            NSMutableDictionary *myDictionary = [[NSMutableDictionary alloc] init];
            NSMutableArray *arrayForCurrentDate = [[NSMutableArray alloc] init];
            NSString *lastDate = [myArray objectAtIndex:0];
            for (int i=0; i< [myArray count]; i++)
            {
                if (![lastDate isEqualToString:[myArray objectAtIndex:i])
                {
                    if ([arrayForCurrentDate count])
                        [myDictionary setObject:arrayForCurrentDate forKey:lastDate];
                    [arrayForCurrentDate removeAllObjects];
                    lastDate [myArray objectAtIndex:i];
                }
                [arrayForCurrentDate addObject:];
            }
            if ([arrayForCurrentDate count])
                  [myDictionary setObject:arrayForCurrentDate forKey:lastDate];

Cheers,
VFN

小ぇ时光︴ 2024-08-26 14:05:40

所以,这是我的最终结果。实际上,我必须按天和月来存储我的对象,而不仅仅是按星期几(原始帖子中不清楚):(

条目是原始数组)

// reverse sort of entries, and put into daily buckets
-(NSMutableArray*) sortedEntries {  
    if (sortedEntries == nil) {
        NSInteger currentDay = -1;
        NSCalendar *gregorian = [NSCalendar currentCalendar];
        NSEnumerator* enumerator = [self.entries reverseObjectEnumerator];
        sortedEntries = [NSMutableArray new];
        DiaryEntry* currentEntry;
        while (currentEntry=[enumerator nextObject])
        {
            NSDate* date = [currentEntry valueForKey:@"date"];
            NSDateComponents *weekdayComponents = [gregorian components:(NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:date];

            NSInteger newDay = [weekdayComponents day];
            if (currentDay == -1 || newDay != currentDay){
                NSMutableArray* dailyArray = [NSMutableArray new];  
                [sortedEntries addObject:dailyArray];
                [dailyArray addObject:currentEntry];
                [dailyArray release];

            } else {
                [[sortedEntries lastObject] addObject:currentEntry];
            }

            currentDay = newDay;
        }
    }

    return sortedEntries;
}

So, here is my final result. I actually had to bucket my objects by day and month, rather than just by the day of week (not clear in original posting):

(entries is the original array)

// reverse sort of entries, and put into daily buckets
-(NSMutableArray*) sortedEntries {  
    if (sortedEntries == nil) {
        NSInteger currentDay = -1;
        NSCalendar *gregorian = [NSCalendar currentCalendar];
        NSEnumerator* enumerator = [self.entries reverseObjectEnumerator];
        sortedEntries = [NSMutableArray new];
        DiaryEntry* currentEntry;
        while (currentEntry=[enumerator nextObject])
        {
            NSDate* date = [currentEntry valueForKey:@"date"];
            NSDateComponents *weekdayComponents = [gregorian components:(NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:date];

            NSInteger newDay = [weekdayComponents day];
            if (currentDay == -1 || newDay != currentDay){
                NSMutableArray* dailyArray = [NSMutableArray new];  
                [sortedEntries addObject:dailyArray];
                [dailyArray addObject:currentEntry];
                [dailyArray release];

            } else {
                [[sortedEntries lastObject] addObject:currentEntry];
            }

            currentDay = newDay;
        }
    }

    return sortedEntries;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文