Objective C - 将对象数组(带有日期字段)转换为数组字典(按星期几键控)
我有一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
以下应该可以工作(实际上没有编译和测试代码)
The following should work (did not actually compile and test the code)
好吧,我假设您的 DiaryEntry 有一个日期属性。这是一个快速但肮脏的版本,你可以让它变得更好。
我会仔细检查代码中的方法名称/编译...我有点即兴发挥,但它基本上是:
浏览列表。对于找到的每个条目,查看是否有与该日期关联的数组。如果没有,请创建它。添加到该数组。
注意 您可能要考虑将结构更改为数组...除非您居住在超过 7 天的土地上,否则您可以存储按特定顺序存储的数组。我尝试尽可能避免地图结构,除非我有大量对象并且我想要快速查找。
Well, I assume your DiaryEntry has a date property. Here's a quick and dirty version, you could make this a lot nicer.
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.
我没有测试它,但我可以编写这段代码,您可以根据需要进行改进。
干杯,
虚拟网络
I didn't test it, but I could wrote this piece of code that you can improve as you need.
Cheers,
VFN
所以,这是我的最终结果。实际上,我必须按天和月来存储我的对象,而不仅仅是按星期几(原始帖子中不清楚):(
条目是原始数组)
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)