Not able to unarchive primitive data in Xcode8 Swift, Archived by Xcode7.3

Primitive data (eg: Int, Float, Double)Data Archived By Xcode7.3 using encodeObject() not able to unarchived using decodeObject(Key:) in Xcode8 Always returns nil


Steps to reproduce:


1. I am archiving model class and saving into a .json file.


If upgrading app after upgrading code in Xcode8 (iOS10) it is crashing first time, Because not able to unarchive Primitive data (eg: Int, Float, Double) type.


Testing Process:

1. Use Xcode7.3 in and run app in simulater save data in .json file.

2. After upgrade open app in Xcode8 and use same simulator app will get crash.


For encoding everywhere I am using:

encodeObject


For Decoding everywhere I am Using:

decodeObject



In Xcode8 decodeObject alwayse returns nil for Primitive data (eg: Int, Float, Double) type

Replies

NSCoding was designed around Objective-C classes and isn’t a great choice for Swift value types, like

Int
and so on. To make this work you’ll have to make sure you carefully convert everything to Foundation class types and back again. For example, this code:
import Foundation

let n = 42 as NSNumber
NSLog("%@", NSKeyedArchiver.archivedDataWithRootObject(n))

produces this data:

2016-09-26 12:09:41.471 xxts2[15792:1234642] <62706c69 73743030
d4010203 04050609 0a582476 65727369 6f6e5824 6f626a65 63747359
24617263 68697665 72542474 6f701200 0186a0a2 07085524 6e756c6c
102a5f10 0f4e534b 65796564 41726368 69766572 d10b0c54 726f6f74
80010811 1a232d32 373a4042 54575c00 00000000 00010100 00000000
00000d00 00000000 00000000 00000000 00005e>

that can be unarchived by this code in Swift 3:

let d = QHex.data("…")
let r = NSKeyedUnarchiver.unarchiveObject(with: d)!
let n = r as! NSNumber
print(n)

where

QHex.data(_:)
converts a string of hex to a
Data
value.

I’m not sure why this is failing in your case. Please post a minimal example of the failing case.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"