swiftstringxcodecore-datauint64

How do you store an UInt64 in CoreData?


My understanding is that a UInt64 can be any value from: 0 to 18446744073709551615

I need to save a UInt64 identifier to CoreData, however the values I see are:

enter image description here

I initially tried Integer 64 but now I am understanding that has a range of: -9223372036854775808 to 9223372036854775807

Do developers usually store an UInt64 as a String and do conversions between the two types? Is this the best practice?


Solution

  • You can (losslessly) convert between UInt64 and Int64:

    // Set:
    obj.int64Property = Int64(bitPattern: uint64Value)
    
    // Get:
    let uint64Value = UInt64(bitPattern: obj.int64Property)
    

    You can define uint64Value as a computed property of the managed object class to automate the conversion:

    @objc(MyEntity)
    public class MyEntity: NSManagedObject {
        
        public var uint64Property: UInt64 {
            get {
                return UInt64(bitPattern: int64Property)
            }
            set {
                int64Property = Int64(bitPattern: newValue)
            }
        }
    }