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:
So, is there any better way?
Use -mutableCopy . NSDictionary *d; NSMutableDictionary *m = [d mutableCopy]; Note that -mutableCopy returns id ( Any in Swift) so you will want to assign / cast to the right type. It creates a shallow copy of the original dictionary.
You have to convert NSDictionary to NSMutableDictionary . You have to user NSMutableDictionary in place of the NSDictionary . After that you can able to change value in NSMutableDictionary . Save this answer.
The NSDictionary class declares the programmatic interface to objects that manage immutable associations of keys and values. For example, an interactive form could be represented as a dictionary, with the field names as keys, corresponding to user-entered values.
[myDictionary setObject:nextValue forKey:myWord]; You can simply say: myDictionary[myWord] = nextValue; Similarly, to get a value, you can use myDictionary[key] to get the value (or nil).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With