S.J S.J - 1 year ago 105
Objective-C Question

How to encode and decode NSCalendarUnit

How to encode and decode

like other objects, like

self.myStr = [decoder decodeObjectForKey:@"myStr"];
[encoder encodeObject:self.myStr forKey:@"myStr"];

Tried to save
like this
but I am getting
when I log.

I want to encode
and save it, later when required decode it and use it for comparison like this
if(xxxxx == NSCalendarUnit)

Answer Source

NSCalendarUnit is an unsigned long, so it can be "boxed" (made into an object) using two methods on NSNumber intended for unsigned longs:

NSCalendarUnit someNSCalendarUnit = NSCalendarUnitDay;
NSNumber *boxed = [NSNumber numberWithUnsignedLong:someNSCalendarUnit];


NSCalendarUnit unboxed = [boxed unsignedLongLongValue];
// now, unboxed == someNSCalendarUnit

And you probably know how to encode an decode NSNumbers, just add the additional box-step to the encode/decode methods...

- (void)encodeWithCoder:(NSCoder*)encoder {
    [super encodeWithCoder:encoder];

    NSNumber *boxed = [NSNumber numberWithUnsignedLong:self.someNSCalendarUnit];
    [encoder encodeObject:boxed forKey:@"someNSCalendarUnit"];
    // ...


- (id)initWithCoder:(NSCoder*)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        NSNumber *boxed = [aDecoder decodeObjectForKey:@"someNSCalendarUnit"];
        _someNSCalendarUnit = [boxed unsignedLongLongValue];
        // ...
    return self;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download