基本上我正在使用一些名为 OrderedDictionary 的开源代码,它是从 NSMutableDictionary 派生的。然后我想通过向 OrderedDictionary 类添加编码和解码方法将有序字典数据保存到 NSUserDefaults。但是,我意识到编码和解码方法没有被调用,因此解码的字典不再是有序的。下面是我的代码:
@interface OrderedDictionary : NSMutableDictionary <NSCopying, NSCoding>
{
NSMutableDictionary *dictionary;
NSMutableArray *array;
}
在实现文件中:
/**
* encode the object
**/
- (void)encodeWithCoder:(NSCoder *)coder
{
[super encodeWithCoder:coder];
[coder encodeObject:dictionary forKey:@"dictionary"];
[coder encodeObject:array forKey:@"array"];
}
/**
* decode the object
*/
- (id)initWithCoder:(NSCoder *)coder
{
self = [super initWithCoder:coder];
if (self != nil)
{
dictionary = [coder decodeObjectForKey:@"dictionary"];
array = [coder decodeObjectForKey:@"array"];
}
return self;
}
使用它的快速示例代码:
dictionary = [[OrderedDictionary alloc] init];
[dictionary setObject:@"one" forKey:@"two"];
[dictionary setObject:@"what" forKey:@"what"];
[dictionary setObject:@"7" forKey:@"7"];
NSLog(@"Final contents of the dictionary: %@", dictionary);
if ([[NSUserDefaults standardUserDefaults] objectForKey:@"myDictionary"] == nil)
{
[[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:dictionary]
forKey:@"myDictionary"];
}
else
{
NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
NSData *savedDictionary = [currentDefaults objectForKey:@"myDictionary"];
if (savedDictionary != nil)
{
OrderedDictionary *oldData = [NSKeyedUnarchiver unarchiveObjectWithData:savedDictionary];
if (oldData != nil)
{
NSLog(@"Final contents of the retrieved: %@", oldData);
}
}
}
问题是,最终的检索字典没有原始数据顺序,并且根本不调用编码和解码方法。
提前感谢您的帮助!:)