如何将NSDateComponents存储到NSUserDefaults中?

时间:2012-07-19 21:57:50

标签: objective-c ios

我想将NSDateComponents存储到NSUserDefaults,所以首先需要将它包装在NSData中,如何做到这一点?

或者有另一种方法将NSDateComponent存储到用户默认值?

1 个答案:

答案 0 :(得分:3)

NSDateComponents符合NSCoding协议,因此您可以使用NSKeyedArchiver / NSKeyedUnarchiver来完成这项工作。以下是一些示例代码:

NSDateComponents *cmp = ...;
//Encoding
NSMutableData *data= [NSMutableData data];

NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];

[archiver encodeObject:cmp];
[archiver finishEncoding];

//Decoding
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];

NSDateComponents *decoded = [unarchiver decodeObject];

[unarchiver finishDecoding];