繁体   English   中英

从 Swift 中的 CoreData 填充 UIPickerview 值

[英]Populating UIPickerview values from CoreData in Swift

我正在尝试使用存储在coreData中的数据填充UIPicker 他们的方法是我已经设置了一个全局变量数组,当屏幕加载时,一个获取请求被发送到填充全局数组的核心数据。 然后UIPicker读取这个全局数组并用它的字符串数组填充自己。

问题是UIPicker在我第一次加载它时填充得很好,但是第二次我重复了原始条目,第三次和第四次等等......

  1. 全局数组:

    var savedWorkoutNamesPulled = [String]()

  2. UIPicker设置:

     //needed picker function (number of columns in picker view) func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } //needed picker function (number of rows in pickr view) func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { savedWorkoutNamesPulled.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { //setting exercisesInSelectedWorkout(exercise names within workout) to the elements of the uipicker let row = savedWorkoutNamesPulled[row] return row }
  3. 调用核心数据 function:

     override func viewDidAppear(_ animated: Bool) { //calling function that deals show picker showUiPicker() //going into core data swift file and calling a function (this function sets global array to fill workout names into picker view) print("your workouts are as follows") CoreDataManager.sharedInstance.retrieveWorkoutDataFromCoreData()

    }

  4. 将值附加到全局数组的核心数据 function:

     func retrieveWorkoutDataFromCoreData() -> [Contact]{ let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "ContactsData") let result = try? context.fetch(fetchRequest) var contacts = [Contact]() for data in result as. [NSManagedObject]{ guard let id = data:value(forKey? "id") as. String else {continue} guard let fullName = data:value(forKey? "fullName") as. String else {continue} guard let excercise = data:value(forKey? "excersizes") as: [Exercise] else {continue} var contact = Contact(id, id: fullname, fullName: exercises. excercise) contact.id = id contacts.append(contact) print(fullName) print(id) savedWorkoutNamesPulled.append(fullName) } return contacts }

当视图被关闭时,我可以通过将数组设置为空来修复它。

override func viewDidDisappear(_ animated: Bool) {
        savedWorkoutNamesPulled = []
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM