Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

float INFINITY can be archived by NSCoder, but not dearchived

I have to archive a float with value INFINITY, and later to dearchive it.
Here is my example code:

Object to be archived:

@interface CodeInf : NSObject <NSCoding>
@end
@implementation CodeInf
- (void)encodeWithCoder:(NSCoder *)encoder {
    float inf = INFINITY;
    [encoder encodeFloat: inf forKey:@"INFINITY"];
}
- (id)initWithCoder:(NSCoder *)decoder {
    if (self = [super init]) {
        float decodedInf = [decoder decodeFloatForKey: @"INFINITY"];
    }
    return self;
}
@end

And here is the archiving/dearchiving code:

CodeInf *myCodeInf = [[CodeInf alloc] init];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:myCodeInf];
myCodeInf = [NSKeyedUnarchiver unarchiveObjectWithData:data];

Archiving works, but dearchiving raises the error:

* Terminating app due to uncaught exception 'NSRangeException', reason: '* -[NSKeyedUnarchiver decodeFloatForKey:]: value (inf) for key (INFINITY) too large to fit in 32-bit float'

Is this a bug in the dearchiver, or do I something wrong?

like image 302
Reinhard Männer Avatar asked Jun 12 '13 07:06

Reinhard Männer


1 Answers

Looks like a bug. Submit a bug report to Apple.

As a workaround use encodeDouble and decodeDoubleForKey - you can keep your value as a float and no casts are needed by C rules.

like image 72
CRD Avatar answered Oct 16 '22 10:10

CRD