核心数据 NSObject 到 Int

Core Data NSObject to Int

我的状态核心数据属性是

因为我想保留状态更改的日志。所以一个值是不够的。

当我将数据写入核心数据时,如下所示

@State var statusIndexEdits : [Int] = []
@State var selectedStatusIndex: Int = 0
.onChange(of: self.selectedStatusIndex) { newValue in
                self.editItem(account: account)
            }
private func editItem(account: CDAccount) {
viewContext.performAndWait {
            if account.statusIndex != selectedStatusIndex {
                account.statusIndex = Int64(selectedStatusIndex)
                statusIndexEdits.append(selectedStatusIndex)
                account.statuses = statusIndexEdits as NSObject
                print(account.statuses!)
            }
            do {
                try viewContext.save()
            } catch {
                let nsError = error as NSError
                fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
            }
    }

我的 print(account.statuses!) 语句打印

statuses = "(\n 4,\n 1,\n 12,\n 1,\n 0,\n 5\n)";

因此,在尝试像下面那样转换我的 account.statuses 时,我无法从中获取 Int 值。

我已尝试通过

达到这些状态指标值
 ForEach(Array(arrayLiteral: account.statuses), id: \.self) { statusIndex in
 trial 1
//Text(self.status[statusIndex as! Int])
 trial 2
//Text("\(statusIndex ?? 0 as NSObject)")
 trial 3
//Text(status[Int("\(statusIndex ?? 0 as NSObject)")!])
 }

顺便说一句,如果你想知道状态到底是什么

@State var status : [String] = Constants.Status.status

    struct Constants {
        struct Status {
            static let status = ["Introduction", "Demonstration", "Offer submitted", "Waiting for reply", "Accepted", "Declined", "Revise offer", "Contract sent", "Contract signed", "Server setup", "Training", "Integration", "Live", "Invoice"]
    }

所以根据状态指数,我达到了 status[statusIndex]

的状态

长话短说,我如何将那些核心数据 NSObject 转换为 Int。因此我可以轻松地使用 status[statusIndex]。

if statuses is [Int]。只需在“Data Model Inspector”中将其定义为“Custom Class”即可。它会像普通数组一样工作