1

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?

1 Answer 1

3

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:

import Foundation

enum PropertyKey: String {
  case numberKey
}

class MyDataModel: NSObject, NSCoding {
  var myNumber: Int64 = 0 // Explicitly provide integer width

  required convenience init?(coder aCoder: NSCoder) {
    guard let myNumber = aCoder.decodeInt64(forKey: PropertyKey.numberKey.rawValue) as Int64? else {
      return nil
    }
    self.init()
    self.myNumber = myNumber
  }

  func encode(with aCoder: NSCoder) {
    aCoder.encode(myNumber, forKey: PropertyKey.numberKey.rawValue)
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Great answer. It makes sense that this would be caused by devices that have 32bits vs 64bits.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.