float INFINITY can be archived by NSCoder, but not dearchived

♀尐吖头ヾ 提交于 2019-12-21 09:21:50

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/17059941/float-infinity-can-be-archived-by-nscoder-but-not-dearchived

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