稱爲基本上我使用一個名爲OrderedDictionary一些開源代碼是從的NSMutableDictionary的。然後,我想通過將編碼和解碼方法添加到OrderedDictionary類來將有序的字典數據保存到NSUserDefaults。但是,我意識到編碼和解碼方法沒有被調用,因此解碼的字典不再被排序。下面是我的代碼:encodeWithCoder沒有在派生類中的NSMutableDictionary
@interface OrderedDictionary : NSMutableDictionary <NSCopying, NSCoding>
{
NSMutableDictionary *dictionary;
NSMutableArray *array;
}
在實現文件:
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);
}
}
}
的事情是,最終retrievedDictionary沒有原文:
使用該/**
* 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;
}
快速示例代碼數據順序以及編碼和解碼方法完全不會被調用。
感謝您提前提供任何幫助! :)
我懷疑有沒有辦法解決這個問題,即我們可能無法調用的NSMutableDictionary的子類的編碼和解碼方法.... – trillions 2012-04-09 17:38:02