Is it possible to add NSDate as keys and some arrays as it values in a NSDictionary?
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
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?
Is it possible to have NSDate as key? Also, what other problems I might face with this assumption?
Thanks,
Raj
Edit: 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);
Output:
Date 1 = 7945610, Date 2 = bd03610
But does the key comparison of NSDictionary interpret these 2 NSDate objects as different?
Another Edit:
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:
- 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!
So, is there any better way?
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.
来源:https://stackoverflow.com/questions/8786398/nsdate-as-keys-for-nsdictionary