I have a CoreData attribute on an entity on which I want to store integer values larger than Int32.max
and UInt32.max
. The value is used as an index, so lookup performance matters. So I've opted to use Integer 64
as datatype in CoreData.
Now I'm struggling on how to store an Int64 on my entity instance. See also the following different approaches I've tried.
Use NSNumber
:
import Foundation
import CoreData
class Node : NSManagedObject {
@NSManaged var id : NSNumber
}
node.id = Int64(1)
> 'Int64' is not convertible to 'NSNumber'
Use NSInteger
:
import Foundation
import CoreData
class Node : NSManagedObject {
@NSManaged var id : NSInteger
}
node.id = Int64(1)
> 'Int64' is not convertible to 'NSInteger'
Use Int64
:
import Foundation
import CoreData
class Node : NSManagedObject {
@NSManaged var id : Int64
}
node.id = Int64(1)
> EXC_BAD_ACCESS (code=1, address=...)
How should the attribute be defined / assigned in order to use 64 bit integers?
A 64-bit signed integer value type.
You can define the "Integer 64" attribute as NSNumber
in the managed object subclass:
@NSManaged var id : NSNumber
Setting a value:
let value:Int64 = 20000000000000000
node.id = NSNumber(longLong: value)
Retrieving the value:
let value:Int64 = node.id.longLongValue
Note that long long
is a 64-bit integer on both the 32-bit and the 64-bit architecture.
Defining the property as
@NSManaged var id : Int64
// ...
node.id = Int64(...)
should also work, because Core Data supports scalar accessor methods for primitive
data types. The EXC_BAD_ACCESS
exception when assigning a value looks to me
like a bug in the Swift compiler or runtime. A similar problem for a Boolean property
is reported here
where a NSNumber
property is reported to work, but the scalar Bool
property
causes the same exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With