如何编码和解码NSCalendarUnit

时间:2016-10-02 13:22:18

标签: ios objective-c nscalendar

如何像其他对象一样对NSCalendarUnit进行编码和解码,例如

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

尝试将NSCalendarUnit NSNumber保存在@(self.repetition); 64,但我在登录时收到NSCalendarUnit

我想对if(xxxxx == NSCalendarUnit)进行编码并保存,以后需要对其进行解码并将其用于比较,如eval

2 个答案:

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