将 Int 保存到核心数据 SWIFTUI

Saving Int to Core Data SWIFTUI

下面是我的任务管理应用程序中的一个视图,我试图让我的选择器在被选中时显示某种颜色。我的问题是如何在核心数据中保存用于优先级和颜色选择器的整数?我不知道如何将 int 值转换为 int32,并且它不能作为 Int32 对象开始,因为那样它就不能用作每个选择器背景颜色的选择器。请帮忙!

struct NewTask: View {
    @Environment(\.dismiss) var dismiss
    
    // MARK: Task Values
    @State var taskTitle: String = ""
    @State var taskDescription: String = ""
    @State var taskDate: Date = Date()
    
    var colors = ["Teal","Yellow","Pink"]
    @State var selectedColor: Int = 0
    
    var colorsColors = ["logoTeal","logoYellow","logoPink"]
    
    var selectedColorInt: String {
        get {
            return ("\(selectedColor)")
        }
    }
    
    var priorities = ["Urgent","Slightly Urgent","Not Urgent"]
    @State var selectedPriority: Int = 0
    
    
    var priorityColors = ["priorityRed","priorityYellow","priorityGreen"]

    
    // MARK: Core Data Context
    @Environment(\.managedObjectContext) var context
    
    @EnvironmentObject var taskModel: TaskViewModel
    var body: some View {
        
        NavigationView{
            List{
                Section {
                    TextField("Go to work", text: $taskTitle)
                    Picker("Priority", selection: $selectedPriority) {
                        ForEach(0..<priorities.count){
                            Text(priorities[[=10=]])
                        }
                        .padding(5)
                        .foregroundColor(.white)
                        .background(priorityColors[selectedPriority])
                        .cornerRadius(5)
                        
                    }
                    Picker("Theme", selection: $selectedColor) {
                        ForEach(0..<colors.count){
                            Text(colors[[=10=]])
                        }
                        .padding(5)
                        .foregroundColor(.black)
                        .background(colorColors[selectedColor])
                        .cornerRadius(5)
                    }
                } header: {
                    Text("Task Information")
                }

                Section {
                    TextEditor(text: $taskDescription)
                } header: {
                    Text("Task Description")
                }
                
                // Disabling Date for Edit Mode
                if taskModel.editTask == nil{
                    
                    Section {
                        DatePicker("", selection: $taskDate)
                            .datePickerStyle(.graphical)
                            .labelsHidden()
                    } header: {
                        Text("Task Date")
                    }
                }
            }
            .listStyle(.insetGrouped)
            .navigationTitle("Add New Task")
            .navigationBarTitleDisplayMode(.inline)
            // MARK: Disbaling Dismiss on Swipe
            .interactiveDismissDisabled()
            // MARK: Action Buttons
            .toolbar {
                
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button("Save"){
                        
                        if let task = taskModel.editTask{
                            
                            task.taskTitle = taskTitle
                            task.taskDescription = taskDescription
                        }
                        else{
                            let task = Task(context: context)
                            task.taskTitle = taskTitle
                            task.taskDescription = taskDescription
                            task.taskDate = taskDate
                            /*task.selectedColor = selectedColor*/
                            /*task.selectedPriority = selectedPriority*/
                        }
                        
                        // Saving
                        try? context.save()
                        // Dismissing View
                        dismiss()
                    }
                    .disabled(taskTitle == "" || taskDescription == "")
                }
                
                ToolbarItem(placement: .navigationBarLeading) {
                    Button("Cancel"){
                        dismiss()
                    }
                }
            }
            // Loading Task data if from Edit
            .onAppear {
                if let task = taskModel.editTask{
                    taskTitle = task.taskTitle ?? ""
                    taskDescription = task.taskDescription ?? ""
                }
            }
        }
    }
    
}

这是我会采用的方法。

首先,由于优先级只会是三个值之一,因此将其表示为具有 Int32 原始值的枚举,并将文本描述和颜色作为枚举的属性:

enum Priority: Int32, CaseIterable {
    case urgent = 0
    case slightlyUrgent = 1
    case notUrgent = 2

    var description: String {
        switch self {
        case .urgent: return "Urgent"
        case .slightlyUrgent: return "Slightly Urgent"
        case .notUrgent: return "Not Urgent"
        }
    }

    var colorName: String {
        switch self {
        case .urgent: return "PriorityRed"
        case .slightlyUrgent: return "PriorityYellow"
        case .notUrgent: return "PriorityGreen"
        }
    }

    var color: Color { Color(colorName) }
}

在表单中,这使您的代码更简洁,并允许您在初始化状态变量时使用 0 上的语义值:

@State private var selectedPriority: Priority = .urgent

Picker("Priority", selection: $selectedPriority) {
  ForEach(Priority.allCases, id: \.self) { priority in
    Text(priority.description)
      .padding(5)
      .foregroundColor(.black)
      .background(priority.color)
      .cornerRadius(5)
  }
}

然后,向您的 CoreData 模型添加一个扩展,使其具有 Priority 属性,添加 getter 和 setter 以便它使用存储的列:

extension Task {
  var priorityEnum: Priority {
    get { Priority(rawValue: priority) ?? .urgent }
    set { priority = newValue.rawValue }
  }
}

然后在将表单详细信息保存到 Core Data 托管对象中时,您可以将 task.priorityEnum 设置为选择器的值,自定义 属性 将确保正确的 Int32 值被存储。

同样,当从任务中加载编辑表单的状态变量时,引用 task.priorityEnum 会得到一个 Priority 值,该值用存储在数据库中的整数初始化。