loyalpenguin loyalpenguin - 1 month ago 6
Swift Question

Encoding and Decoding Int Values between iOS and macOS

I'm developing an app that will share data cross platform specifically between iOS and macOS. I'm using NSCoding to serialize my model to a file. A specific property in my data model is of type Int. Below is a section of code that runs on both iOS and macOS:

class MyDataModel: NSObject, NSCoding {
struct Keys {
static let myNumber = "myNumber"
}

var myNumber: Int = 0

required init(coder aCoder: NSCoder) {
super.init()
myNumber = aDecoder.decodeInteger(PropertyKey.nameKey)
}

fun encode(with aCoder: NSCoder) {
aCoder.encodeInteger(myNumber, forKey: PropertyKey.ratingKey)
}
}


The question is, if I save this integer on iOS into a file on iCloud, and then open the file and decode in on macOS will the data remain the same? I have heard rumors that
Int
are interpreted differently on these two platforms. I was even recommended to store my integers as strings and then cast them into an integer. Could someone confirm whether this is true or not?

Answer

The only issue that I can think of is that you may run into issues with 32 bit vs 64 bit environments. An Int will change maximum size between the two and you may get odd results when it goes from 64 bit to 32 bit.

What you can do to protect against this is use a specific type of Int such as Int32 or Int64. This should work properly across all environments. You can then cast to Int in your code, handling any overflow properly.

Example:

class MyDataModel: NSObject, NSCoding {
   struct Keys {
      static let myNumber = "myNumber"
   } 

   var myNumber: Int64 = 0 // Explicitly provide integer width

   required init(coder aCoder: NSCoder) {
      super.init()
      myNumber = aCoder.decodeInt64(forKey: PropertyKey.nameKey)
   }

   fun encode(with aCoder: NSCoder) {
      aCoder.encode(myNumber, forKey: PropertyKey.ratingKey)
   }
}
Comments