If at all possible, when writing data to disk or across a network, it s best to be explicit about the size of value. Instead of using NSUInteger as the datatype, use uint16_t
, uint32_t
, or uint64_t
depending on the range you need. This then naturally translates to Integer 16, 32, and 64 in Core Data.
理解为什么考虑这一设想:
- You opt to use Integer 64 type to store your value.
- On a 64-bit iOS device (eg iPhone 6) it stores the value 5,000,000,000.
- On a 32-bit iOS device this value is fetched from the store into an
NSUInteger
(using NSNumber s unsignedIntegerValue
).
现在,由于NSUInteger在32个轨道装置上仅限32个轨道,因此该数字已不超过5 000 000 000 000 000 000 000 000美元,因为只有一定比例的限额才能达到50亿。 如果您在步骤3中转换了NUInteger
,uint64_t
。 这样,价值仍将是50亿美元。
如果你绝对必须使用NSUInteger,那么你就有理由对上文所述问题持怀疑态度,并为之提供防御。
在将未签字的数值储存到似乎已签署的核心数据类型方面,你可以安全储存这些数值并检索:
NSManagedObject *object = // create object
object.valueNumber = @(4000000000); // Store 4 billion in an Integer 32 Core Data type
[managedObjectContext save:NULL] // Save value to store
// Later on
NSManagedObject *object = // fetch object from store
uint32_t value = object.valueNumber.unsignedIntegerValue; // value will be 4 billion