我想将NSDateComponents存储到NSUserDefaults,所以首先需要将它包装在NSData中,如何做到这一点?
或者有另一种方法将NSDateComponent存储到用户默认值?
答案 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];