簡體   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