如何像其他对象一样对NSCalendarUnit
进行编码和解码,例如
self.myStr = [decoder decodeObjectForKey:@"myStr"];
[encoder encodeObject:self.myStr forKey:@"myStr"];
尝试将NSCalendarUnit
NSNumber
保存在@(self.repetition);
64
,但我在登录时收到NSCalendarUnit
。
我想对if(xxxxx == NSCalendarUnit)
进行编码并保存,以后需要对其进行解码并将其用于比较,如eval
答案 0 :(得分:1)
NSCalendarUnit
是一个选项集(NS_OPTIONS
),这意味着NSCalendarUnit
值可以是单位的无,一个或多个值。
您需要执行bit mask if ((xxxx & NSCalendarUnitHour) != 0)
来检查值。
您可以像现在一样对值进行编码,NSNumber
并使用NSNumber.unsignedInteger
在解码时获取值(请注意NSCalendarUnit
的枚举定义为NSUInteger
)。 (注意,您还可以使用-[NSCoder encodeInteger:forKey:]
将值存储为NSInteger
。)
<强>序列化强>
[encoder encodeObject:@(self.repetition) forKey:@"repetition"];
<强> Deserialisation 强>
self.repetition = [[decoder decodeObjectOfClass:[NSNumber class]
forKey:@"repetition"] unsignedInteger];
<强>检查强>
if ((self.repetition & NSCalendarUnitHour) != 0) {
// Do something
} else if ((self.repetition & NSCalendarUnitMinute) != 0) {
// Do something
}
答案 1 :(得分:1)
NSCalendarUnit
是一个无符号长整数,所以它可以是#34;盒装&#34; (在一个对象中)使用NSNumber
上用于无符号长整数的两种方法:
NSCalendarUnit someNSCalendarUnit = NSCalendarUnitDay;
NSNumber *boxed = [NSNumber numberWithUnsignedLong:someNSCalendarUnit];
和
NSCalendarUnit unboxed = [boxed unsignedLongLongValue];
// now, unboxed == someNSCalendarUnit
您可能知道如何编码解码NSNumbers,只需在编码/解码方法中添加额外的步骤...
- (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;
}