2016-10-02 63 views
1

如何編碼,並像其他對象進行解碼NSCalendarUnit,像如何編碼和解碼NSCalendarUnit

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

試過在NSNumber保存NSCalendarUnit這樣@(self.repetition);但我正在逐漸64當我登錄。

欲編碼NSCalendarUnit並保存,以後需要解碼它,當和使用它的像這樣if(xxxxx == NSCalendarUnit)

回答

1

NSCalendarUnit是一個無符號長,所以使用上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; 
} 
1

NSCalendarUnit比較的選項集(NS_OPTIONS),這意味着一個NSCalendarUnit值可以是零個,一個或更多的單位價值。 您需要執行bit maskif ((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 
}