问题
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 decodeIntFromKey
etc. But for objects one has to call decodeObject
or 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