[英]Populating UIPickerview values from CoreData in Swift
I am trying to populate a UIPicker
with data that is stored in coreData
.我正在尝试使用存储在
coreData
中的数据填充UIPicker
。 they way i have gone about this is i have set up a global variable array and when the screen loads a fetch request is sent to core data which populates the global array.他们的方法是我已经设置了一个全局变量数组,当屏幕加载时,一个获取请求被发送到填充全局数组的核心数据。 The
UIPicker
then reads this global array and populates itself with its array of strings.然后
UIPicker
读取这个全局数组并用它的字符串数组填充自己。
the problem is that the UIPicker
populates fine the first time i load it, but then the second time i get the original entries repeated, and the 3rd time and 4th etc...问题是
UIPicker
在我第一次加载它时填充得很好,但是第二次我重复了原始条目,第三次和第四次等等......
global array:全局数组:
var savedWorkoutNamesPulled = [String]()
UIPicker
set up: 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 }
Calling coredata function:调用核心数据 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()
} }
The core data function that appends values to global array:将值附加到全局数组的核心数据 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 }
I was able to fix it by just by setting the array to nothing when the view was dismissed.当视图被关闭时,我可以通过将数组设置为空来修复它。
override func viewDidDisappear(_ animated: Bool) {
savedWorkoutNamesPulled = []
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.