如何在 Swift Int64 中使用 Core Data Integer 64? [英] How to use Core Data Integer 64 with Swift Int64?
问题描述
我有一个实体的 CoreData 属性,我想在该实体上存储大于 Int32.max
和 UInt32.max
的整数值.该值用作索引,因此查找性能很重要.所以我选择在 CoreData 中使用 Integer 64
作为数据类型.
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.
现在我正在努力研究如何在我的实体实例上存储 Int64.另请参阅我尝试过的以下不同方法.
Now I'm struggling on how to store an Int64 on my entity instance. See also the following different approaches I've tried.
使用NSNumber
:
import Foundation
import CoreData
class Node : NSManagedObject {
@NSManaged var id : NSNumber
}
node.id = Int64(1)
> 'Int64' is not convertible to 'NSNumber'
使用NSInteger
:
import Foundation
import CoreData
class Node : NSManagedObject {
@NSManaged var id : NSInteger
}
node.id = Int64(1)
> 'Int64' is not convertible to 'NSInteger'
使用Int64
:
import Foundation
import CoreData
class Node : NSManagedObject {
@NSManaged var id : Int64
}
node.id = Int64(1)
> EXC_BAD_ACCESS (code=1, address=...)
应该如何定义/分配属性才能使用 64 位整数?
How should the attribute be defined / assigned in order to use 64 bit integers?
推荐答案
您可以在托管对象子类中定义Integer 64"属性为NSNumber
:
You can define the "Integer 64" attribute as NSNumber
in the managed object subclass:
@NSManaged var id : NSNumber
设置一个值:
let value:Int64 = 20000000000000000
node.id = NSNumber(longLong: value)
检索值:
let value:Int64 = node.id.longLongValue
请注意,long long
在 32 位和 64 位架构上都是 64 位整数.
Note that long long
is a 64-bit integer on both the 32-bit and the 64-bit architecture.
定义属性为
@NSManaged var id : Int64
// ...
node.id = Int64(...)
应该也可以,因为 Core Data 支持原始数据的标量访问器方法数据类型.分配值时的 EXC_BAD_ACCESS
异常在我看来就像 Swift 编译器或运行时中的错误.布尔属性的类似问题报告在这里
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
其中 NSNumber
属性被报告工作,但标量 Bool
属性导致同样的异常.
where a NSNumber
property is reported to work, but the scalar Bool
property
causes the same exception.
这篇关于如何在 Swift Int64 中使用 Core Data Integer 64?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!