NSDate作为NSDictionary的键 [英] NSDate as keys for NSDictionary
问题描述
是否可以添加NSDate作为键和一些数组作为其值在NSDictionary中?
Is it possible to add NSDate as keys and some arrays as it values in a NSDictionary?
我没有任何要求将字典写入磁盘 - 归档或unarchive,就像这个家伙需要它: NSDictionary与NSDates作为键
I dont have any requirement of writing the dictionary to disk - archiving or unarchiving, just as this guy needs it: NSDictionary with NSDates as keys
但是,为什么我要NSDate被添加为键,具体是这样,我可以从字典中获取所有的键,并做一些计算,从一个范围内获取日期。
But, why I want NSDate to be added as keys specifically is so that I can fetch all keys from the dictionary and do some computations like, fetching the dates from within a range.
是否两个具有相同日期值的对象在创建时共享相同的内存?
Whether two objects with same date value share same memory when created?
是否可以使用NSDate作为键?
Is it possible to have NSDate as key? Also, what other problems I might face with this assumption?
感谢,
Raj
编辑:
发布我的问题后,我只是写了一个示例代码:
After posting my question, I just wrote a sample code:
NSDateComponents *dateComps = [[NSDateComponents alloc] init];
[dateComps setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
[dateComps setDay:1];
[dateComps setMonth:1];
[dateComps setYear:2012];
NSDate *date1 = [[NSCalendar currentCalendar] dateFromComponents:dateComps];
NSDate *date2 = [[NSCalendar currentCalendar] dateFromComponents:dateComps];
NSLog(@"Date 1 = %x, Date 2 = %x", date1, date2);
输出:
Date 1 = 7945610, Date 2 = bd03610
但是NSDictionary解释这两个NSDate对象是不同的?
But does the key comparison of NSDictionary interpret these 2 NSDate objects as different?
另一个编辑:
如果我应该使用NSDateFormatter转换NSDate到NSString,我不能直接检查范围内的日期。我将必须执行以下步骤:
Also, if I should convert NSDate to NSString using NSDateFormatter, I cannot directly check for dates within range. I will have to perform the following steps:
- 从字典获取所有NSString数组键
- 将它们转换回NSDate数组
- 在范围内执行谓词和获取日期
- 再次将这些日期转换为字符串数组
- 现在使用这个字符串键从字典中获取值!
- Get all NSString array of keys from dictionary
- Convert them back to array of NSDate
- Perform predicates and fetch dates within range
- Again convert back those dates to an array of Strings
- Now use this string keys to get values from dictionary!
/ p>
So, is there any better way?
推荐答案
是, NSDate
对象可以用作 NSDictionary
- 任何对象类型都可以用作键,只要它支持 NSCopying
协议。使用 isEqual:
和不通过指针值比较键。有关更多详细信息,请参阅 NSDictionary
文档中的概述部分。
Yes, NSDate
objects can be used as keys for NSDictionary
- any object type can be used as a key provided it supports the NSCopying
protocol. Keys are compared using isEqual:
and not by pointer value. See the Overview section of the NSDictionary
documentation for more details.
这篇关于NSDate作为NSDictionary的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!