[英]How do you store an UInt64 in CoreData?
您可以(無損)在UInt64
和Int64
之間進行轉換:
// Set:
obj.int64Property = Int64(bitPattern: uint64Value)
// Get:
let uint64Value = UInt64(bitPattern: obj.int64Property)
您可以將uint64Value
定義為托管 object class 的計算屬性以自動進行轉換:
@objc(MyEntity)
public class MyEntity: NSManagedObject {
public var uint64Property: UInt64 {
get {
return UInt64(bitPattern: int64Property)
}
set {
int64Property = Int64(bitPattern: newValue)
}
}
}
Martin R
接受的答案將起作用。
但是,這似乎是 Apple 對@NSManaged
屬性的默認實現的一部分。
我是這樣測試的:
Hello
的實體。short
的屬性,保存為Integer 16
。Manual/None
Hello
創建了手冊 class 文件,如下所示:class Hello: NSManagedObject {
@NSManaged var short : UInt16
}
您會注意到我將其輸入為無符號UInt16
。
在我的 AppDelegate 中:
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Get Context
let context = self.persistentContainer.viewContext
// Create Test Objects
let hello1 = Hello(entity: Hello.entity(), insertInto: context)
hello1.short = 255
let hello2 = Hello(entity: Hello.entity(), insertInto: context)
hello2.short = 266 // Should overflow Int16
let hello3 = Hello(entity: Hello.entity(), insertInto: context)
hello3.short = 65535 // Should overflow Int16 by a lot
// Save them to the database
do {
try context.save()
} catch {
print(error)
}
// Fetch the save objects
let fetch = NSFetchRequest<Hello>(entityName: "Hello")
if let results = try? context.fetch(fetch) {
for result in results {
print(result.short)
}
}
}
這會打印出以下內容:
255
266
65535
我想這是有人希望在 Core Data 中保存無符號整數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.