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)
NSCalendarUnit
is an option set ( NS_OPTIONS
), which means a NSCalendarUnit
value can be none, one, or more values of the units. You'll need to do a bit mask if ((xxxx & NSCalendarUnitHour) != 0)
to check for values.
You're fine encoding the value like you are now, as a NSNumber
and using NSNumber.unsignedInteger
to get the value when decoding (note that the enum for NSCalendarUnit
is defined as a NSUInteger
). (Note you can also store the value as a NSInteger
using -[NSCoder encodeInteger:forKey:]
.)
Serialisation
[encoder encodeObject:@(self.repetition) forKey:@"repetition"];
Deserialisation
self.repetition = [[decoder decodeObjectOfClass:[NSNumber class]
forKey:@"repetition"] unsignedInteger];
Checking
if ((self.repetition & NSCalendarUnitHour) != 0) {
// Do something
} else if ((self.repetition & NSCalendarUnitMinute) != 0) {
// Do something
}
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.