Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Core Data Integer 64 with Swift Int64?

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?

like image 718
Bouke Avatar asked Jun 22 '14 11:06

Bouke


People also ask

What is Int64 in Swift?

A 64-bit signed integer value type.


1 Answers

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

  • EXC_BAD_ACCESS error when trying to change Bool property

where a NSNumber property is reported to work, but the scalar Bool property causes the same exception.

like image 104
Martin R Avatar answered Sep 20 '22 22:09

Martin R