在代码中使用通用 Int - 在 Core Data iOS 中使用 32 位或 64 位 Int? [英] Using generic Int in code - Use 32 or 64 bit Int in Core Data iOS?

查看:22
本文介绍了在代码中使用通用 Int - 在 Core Data iOS 中使用 32 位或 64 位 Int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 swift 编写一个应用程序,它通过苹果的核心数据保存其数据.在我的代码中,所有整数都被声明为Int",因为这样更灵活,编译器会根据代码运行的设备调整这些整数.

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.

但是,当我想使用核心数据保存这些Int"时,我必须选择 32 位或 64 位整数.如果可能的话,我希望我的应用程序与 iphone 5-6s 兼容,因此我对选择 32 位犹豫不决(我读过 Apple 由于更好的性能而在 6s 中移至 32 位).

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).

是否有任何解决方法可以保持这部分代码的灵活性?如果我选择 32bit,如果代码在 64bit 设备上运行会发生什么?

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?

提前致谢.

推荐答案

默认 Int:

  • 在 32 位设备上 = Int32
  • 在 64 位设备上 = Int64(是的,它是一个 Int64,只是在我的 iPhone6S 上进行了测试)

但是 Int32 和 Int64 都可以在 32 位设备上运行.(但 Int64 在 32 位设备上计算需要更长的时间)

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

如果您的数字小于或等于 ±2.147.483.647,我建议您使用 Int32
公式:(2^(Bit - 1) - 1)甚至 Int16 如果小于或等于 ±32.767
(实际上负值可以比正值大1:Int32范围 -2.147.483.648 ... 2.147.483.647)

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)

如果您在 coreData 中使用 Int32,请确保您不超过此数字并将 Int 转换为?Int32 保存时(如?因为理论上可以是更大的数字)
当将 Int32 加载到 Int 时总是成功(使用:as!Int)

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)

如果您在 coreData 中使用 Int64,只需将 Int 转换为!Int64 保存时(即使在 32 位设备上也总是会成功,但可能稍微慢一些,但如果你不保存/加载它,你不应该有任何问题)
但是加载时要小心,转换形式 Int64 到 Int 可能会失败,因为理论上 Int64 可以存储更多的数字,32 位设备上的 Int 可以存储(使用 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)

这篇关于在代码中使用通用 Int - 在 Core Data iOS 中使用 32 位或 64 位 Int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆