NSDate as keys for NSDictionary

坚强是说给别人听的谎言 提交于 2019-12-07 07:10:24

问题


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:

  1. Get all NSString array of keys from dictionary
  2. Convert them back to array of NSDate
  3. Perform predicates and fetch dates within range
  4. Again convert back those dates to an array of Strings
  5. Now use this string keys to get values from dictionary!

So, is there any better way?


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!