Determine class while decoding object

亡梦爱人 提交于 2019-12-22 18:09:32

问题


For dealing with (a couple of) legacy communication protocols I try to subclass NSCoder. While the coding works fine, I have some issues with decoding: The protocol does not keep any type information, but a receiver "knows" the structure of a message. I wonder, how the decoder can determine which class an object (property) belongs to.

For C types, this isn't really an issue because one can call decodeIntFromKeyetc. But for objects one has to call decodeObjector decodeObjectForKey:. The documentation tells, that NSCoder's implementation calls decodeValueOfObjCType:at:, i.e. it knows about the type. Maybe this information is stored within the archiver,etc. but this isn't true in my case.

Right now, I am telling the coder what is the class of the next property:

-(id)initWithCoder:(NSCoder *)aDecoder{
    if ([super init] != nil) {
        [aDecoder nextClass:[propertyA class]];
        [self setProperyA: [aDecoder decodeObjectForKey:kKeyPropA]];
        [aDecoder nextClass:[propertyB class]];
        [self setProperyB: [aDecoder decodeObjectForKey:kKeyPropB]];
        // etc.
    }
    return self; 
}

I guess, this isn't a very elegant solution. The only other way I came up with is to "misuse" the key for type information. However, in my case I need the key to determine the relevant object in the protocol.

Thus my question: Is there an elegant way for the decoder to determine the type of the object to decode, e.g., by calling back the owning object?

来源:https://stackoverflow.com/questions/10410343/determine-class-while-decoding-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!