I have a variable
var pausedTime: TimeInterval?
I want to encode & decode it with NSSecureCoding
So far I have this for encoding:
aCoder.encode(pausedTime, forKey: "Pause")
and this for decoding, treating the TimeInterval
as a Double
:
if aDecoder.containsValue(forKey: "Pause") {
pausedTime = aDecoder.decodeDouble(forKey: "Pause")
}
But this is not working and resulting in the error:
[error] fault: exception raised during multi-threaded fetch *** -[NSKeyedUnarchiver decodeDoubleForKey:]: value for key (pausedTime) is not a 64-bit float ({ "__NSCoderInternalErrorCode" = 4864; })
Please could someone provide me with the correct way to secure encode/decode a TimeInterval
?
First, TimeInterval
is exactly a Double
(it's just a typealias). This is useful to know in case you expect any specialness about TimeInterval
. There isn't any.
In your case, pausedTime
is not a TimeInterval
, however. It's a TimeInterval?
. You're probably winding up calling the encode(Any?, forKey:)
overload, and that's probably boxing your double into an NSNumber
.
To fix that, you should make sure you're encoding a Double
. For example:
if let pausedTime = pausedTime {
aCoder.encode(pausedTime, forKey: "Pause")
}
or
aCoder.encode(pausedTime ?? 0.0, forKey: "Pause")