继承NSMutableDictionary并使用NSKeyedArchiver序列化的自定义对象无法反序列化

时间:2017-03-19 11:28:18

标签: objective-c nsmutabledictionary nscoding nskeyedarchiver nskeyedunarchiver

类未正确归档。 请参阅下面的代码示例。

+ git pull origin master
Permission denied (publickey).
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.

在unarchiveObjectWithData调用之后,dict包含对键@“some”但对象是NSMutableDictionary而不是A类。虽然unarchiveObjectWithData调用没有发生initWithCoder调用。 那么,如何使代码工作?为什么继承NSMutableDictionary的类没有反序列化?

1 个答案:

答案 0 :(得分:0)

此方法:

- (void)encodeWithCoder:(NSCoder *)aCoder
{
}

包含对象自身编码的说明,也就是说,"不做任何事情"。应该说的是:

- (void)encodeWithCoder:(NSCoder *)aCoder
{
    // perform the inherited behavior or encoding myself
    [super encodeWithCoder:encoder];
}

再次编辑,这个测试类以最微不足道的方式对NSMutableDictionary进行子类化:通过在其实现中隐藏可变字典实例并提供原始方法(PLUS { {1}})

encodeWithCoder

再次编辑,这次完全是您的测试:

#import "MyDict.h"

@interface MyDict ()
@property(strong) NSMutableDictionary *internalDictionary;
@end

@implementation MyDict

// changed to the default init for the "new" constructor
- (id)init {
    self = [super init];
    if (self) {
        _internalDictionary = [[NSMutableDictionary alloc] init];
    }
    return self;
}

- (NSUInteger)count {
    return [self.internalDictionary count];
}

- (id)objectForKey:(id)aKey {
    return [self.internalDictionary objectForKey:aKey];
}

- (void)setObject:(id)anObject forKey:(id<NSCopying>)aKey {
    return [self.internalDictionary setObject:anObject forKey:aKey];
}

- (void)removeObjectForKey:(id)aKey {
    return [self.internalDictionary removeObjectForKey:aKey];
}

- (NSEnumerator *)keyEnumerator {
    return [self.internalDictionary keyEnumerator];
}

// added encoding of the internal representation
- (void)encodeWithCoder:(NSCoder *)aCoder {
    [super encodeWithCoder:aCoder];
    [aCoder encodeObject:_internalDictionary forKey:@"internalDictionary"];
}

// added decoding of the internal representation
- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        _internalDictionary = [aDecoder decodeObjectForKey:@"internalDictionary"];
    }
    return self;
}

- (Class)classForCoder {
    return self.class;
}

@end

...日志

  

{       some = {           嗨=那里;       }; }