NSDate as keys for NSDictionary

Is it possible to add NSDate as keys and some arrays in NSDictionary values?

I have no requirement to write the dictionary to disk - archiving or disassembling, just like this guy needs it: NSDictionary with NSDates as keys

But why do I want NSDate to be added as keys specifically so that I can extract all the keys from the dictionary and perform some calculations, for example, choosing a date from a range.

If two objects with the same date value use the same memory when creating?

Is it possible that NSDate is the key? Also, what other problems can I encounter with this assumption?

Thanks,

Rajah

Edit: After submitting my question, I just wrote an example 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 NSDictionary key comparison compare these two NSDate objects as different?

Other Edit:

Also, if I have to convert NSDate to NSString using NSDateFormatter, I cannot directly check dates within a range. I have to follow these steps:

  • Get the entire array of NSString keys from a dictionary
  • Convert them back to an NSDate array
  • Perform predicates and select dates within a range
  • Convert these dates again to an array of strings.
  • Now use these string keys to get the values ​​from the dictionary!

So is there a better way?

+4
source share
1 answer

Yes, NSDate objects can be used as keys for NSDictionary - any type of object can be used as a key, provided that it supports the NSCopying protocol. Keys are compared using isEqual: and not by pointer value. See the Overview section of the NSDictionary .

+7
source

Source: https://habr.com/ru/post/1390010/


All Articles