I'm exploring the idea of subclassing NSCoder
to read/write a proprietary file format. I'm starting to believe this might also require me to subclass NSArray
and NSDictionary
to override encodeWithCoder:
to ensure they are encoded properly:
- (void)encodeWithCoder:(NSCoder *)encoder {
if ([encoder isKindOfClass:[CustomCoder class]]) {
// call [encoder encode...] as I see fit.
}else
[super encodeWithCoder:encoder];
}
I'm reluctant to do this because NSCoder
and its related protocols NSCoding
should be self-sufficient... Requiring subclassing classes following the protocol seems like bad design. Am I missunderstanding or over-thinking something?!?
Elaborating a little:
For example, if the file format stipulates that lists of items are encoded like so:
... // rest of file
0xA1 // marks the beginning of a list
0x0010 // amount of item in list. The list contains 16 items in this example.
... // encoded items follows
I would imagine that to encode an array, it's encodeWithCoder:
would need to look like this:
- (void)encodeWithCoder:(NSCoder *)encoder {
[encoder encodeValueOfObjCType:@encode(short) at:&itemCount];
for ( /*for each item of the array*/ ) {
[item encodeWithCoder:encoder];
}
}
Because I ignore how NSArray's encodeWithCoder:
is implement, I imagine I'd have to override it to use my NSCoder class properly.