I have the following class that implements NSCoding
and I have created several instances of it and persisted them to file.
@interface BiscuitTin ()
@property NSString *biscuitType;
@property int numBiscuits;
@end
@implementation BiscuitTin
- (id)initWithCoder:(NSCoder *)coder {
self = [super init];
if (self) {
self.biscuitType = [coder decodeObjectForKey:@"biscuitType"];
self.numBiscuits = [coder decodeIntForKey:@"numBiscuits"];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *coder) {
[coder encodeObject:self.biscuitType forKey:@"biscuitType"];
[coder encodeInt:self.numBiscuits forKey:@"numBiscuits"];
}
@end
I have now decided that I wish to represent numBiscuits
as a float
(as there may be a partially eaten biscuit). Updating the property type and encodeWithCoder
works fine but when I try to load an existing instance from file the app crashes as it's trying to decode an int
and a float
.
Is there a nice way to handle this? Ideally I would be able to load the existing int
value and convert it to a float
, but I wouldn't mind just using a default value and not crashing.
I've considered wrapping the applicable decode
line in a try-catch but in my actually use case there are about 50 or so properties that are being encoded/decoded and it would be nice not to have to have explicit handling for each one that ever changes type.
else if
for key@"numBiscuits2"
– Showalter