S.J S.J - 2 months ago 17
Objective-C Question

How to encode and decode NSCalendarUnit

How to encode and decode

NSCalendarUnit
like other objects, like

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


Tried to save
NSCalendarUnit
in
NSNumber
like this
@(self.repetition);
but I am getting
64
when I log.

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

Answer

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];

and

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;
}