core-dataswiftuinsobject

Core Data NSObject to Int


My core data attribute for statuses is

enter image description here

because I want to keep the logs of the status changes. So one value won't be sufficient.

when I write data to core data like below

@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)")
            }
    }

My print(account.statuses!) statement prints

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

So while trying to convert my account.statuseslike below I can not get Int values from it.

I have tried to reach those status index values with

 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)")!])
 }

Btw if you want to know what the heck is status it is

@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"]
    }

So according to the status index, I am reaching its status with status[statusIndex]

So long story short how can I convert those core data NSObject to Int. Thus I can use status[statusIndex] easily.


Solution

  • if statuses is [Int]. Just define it as the "Custom Class" in the "Data Model Inspector". It will work like a regular array

    enter image description here