将 NSManagedObject 数组添加到 pickerview 的问题

Issue with adding an NSManagedObject array to pickerview

我有一个 pickerview,我在 pickerview 中填充了它的数据 didSelectRow...

myTextField.text = self.myArray[row]

最初myArray是字符串类型。所以一切正常。但是现在 myArrayNSManagedObject 类型。所以它不接受。关于如何解决此问题的任何想法..?

编辑: 这就是我从选择器视图访问数组的方式

   func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        if self.appDelegate.commonProductCategArray.count == 0 {
                // An alert message shown here.
        } else {

            let person = self.appDelegate.commonProductCategArray[row]

            categListTextField.text = person.value(forKey: "categoryName") as? String

        }
    }

在这里,commonProductCategoryArray 在向数据库添加记录时从另一个视图控制器获取它的值,就像这样..

 try managedContext.save()
 self.mangObjArr.append(category as! Category)
 self.appDelegate.commonProductCategArray = self.mangObjArr

选择器视图仅在其组件标签中显示 String,因此您需要从 NSManagedObject.

中获取字符串

textfield.text = managedObject.value(forKeyPath: "keyName") as? String

根据苹果文档:https://developer.apple.com/documentation/coredata/nsmanagedobject

在某些方面,NSManagedObject 就像一本字典——它是一个通用容器 object,可以有效地为其关联的 NSEntityDescription object.

定义的属性提供存储。

所以你可以从它的 keyPath 中获取一个值。

编辑: 您正在获取正确的数据。因此它显示在 textfield 中,但您忘记在选择器视图标题中更新它。

执行那个工具:

public func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
       if !self.appDelegate.commonProductCategArray.isEmpty {
            let person = self.appDelegate.commonProductCategArray[row]
            return person.value(forKey: "categoryName") as? String
       }
       return ""
}

这里出现的第一个问题是如果您不知道如何从 PickerView

中获取字符串值,您如何在 PickerView 中显示数据

然而,它就像从普通字符串数组中获取数据一样简单

假设您在选择器视图中使用 name 属性

显示 Person Class 对象

因为每个 NSManagedObject 子类都包含您在创建架构时定义的属性

你的数组像

var array = [NSManagedObject]()

你只要用正确的方式解析就可以了

(array.first as! Person).name 

你很有价值!!!