Using generic Int in code - Use 32 or 64 bit Int in Core Data iOS?

十年热恋 提交于 2019-12-24 01:13:09

问题


I am writing an app in swift that saves its data through apple's core data. In my code, all integers are just declared as "Int", because that is more flexible and the compiler adapts those ints to the device the code runs on.

However, when I want to save these "Int"s using core data, I have to chose either 32 or 64 bit Integers. I would want my app to be compatible with iphone 5-6s if possible and am therefore hesitant to go for the 32bit(I read Apple moved to 32bit in 6s because of better performance).

Any workarounds to keep this part of the code flexible? If I select 32bit, what will happen if the code is run on a 64bit device?

Thanks in advance.


回答1:


The default Int:

  • on 32 Bit Devices = Int32
  • on 64 Bit Devices = Int64 (and yes it's an Int64 just testet it on my iPhone6S)

But both Int32 and Int64 will work on an 32 Bit device. (But Int64 takes longer to calculate on 32 Bit devices)

I recommend you using Int32 if your number is smaller or equal to ±2.147.483.647
Formula: (2^(Bit - 1) - 1) Or even Int16 if smaller or equal to ±32.767
(Actually the negative Value can be 1 greater than the positiv value: Range of Int32 -2.147.483.648 ... 2.147.483.647)

If you use Int32 in coreData just make sure that you don't exceed this number and cast the Int as? Int32 when saving (as? because it theoretically can be a higher number)
When loading Int32 to Int always succeeds (use: as! Int)

If you use Int64 in coreData just cast the Int as! Int64 when saving (This will always succeed even on 32-Bit devices, but might be a slightly slower but if you don't save/load it to ofter you shouldn't have any problems)
But be careful when loading, the cast form Int64 to Int might fail because again Int64 could theoretically have a greater number stored that an Int on 32-Bit devices can store (use as? Int to prevent possible crashes)



来源:https://stackoverflow.com/questions/37050041/using-generic-int-in-code-use-32-or-64-bit-int-in-core-data-ios

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