簡體   English   中英

你如何在 CoreData 中存儲 UInt64?

[英]How do you store an UInt64 in CoreData?

我的理解是 UInt64 可以是從 0 到 18446744073709551615 之間的任何值

我需要將 UInt64 標識符保存到 CoreData,但是我看到的值是:

在此處輸入圖像描述

我最初嘗試了 Integer 64 但現在我知道它的范圍是:-9223372036854775808 到 9223372036854775807

開發人員通常將 UInt64 存儲為 String 並在兩種類型之間進行轉換嗎? 這是最佳做法嗎?

您可以(無損)在UInt64Int64之間進行轉換:

// 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屬性的默認實現的一部分。

我是這樣測試的:

  1. 我使用 Core Data 創建了一個新的 Xcode 項目,並制作了一個名為Hello的實體。
  2. 它有一個名為short的屬性,保存為Integer 16
  3. 將 Codegen 標記為Manual/None
  4. 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM