所以我正在开发一个计算器应用程序,当涉及到我的UIPickerView和我的核心数据时,我遇到了麻烦。我目前已对其进行设置,以便用户可以使用核心数据实体保存设置。这还将实体的名称属性推送到数组。然后,UIPickerView使用数组中的名称使用选定的核心数据实体自动填充字段。但是,我当前使用的数组在关闭应用程序后不会保留。我正在寻找一种将名称属性推送到数组的方式,以使数组在重新启动应用程序后存储数据。这样,UIPickerView可以在重新启动后访问名称。
这是我目前的处事方式。
var pickerOptions = ["none"]
...
@IBAction func saveSettings (_ sender: Any){
...code to save settings...
coreDataManager.shared.createSetting(power: power, name:name)
pickerOptions.append(name)
}
func numberOfcomponents(in pickerView: UIPickerView)-> Int {
return 1}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component:Int) ->Int{
return pickerOptions.count}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, inComponent component: Int){
return pickerOptions[row]}
func pickerView(_ pickerView: UIPickerView, didSelectRow row:Int, inComponent component: Int){
let setting = coreDataManager.shared.fetchSetting(withName: pickerOptions[row])
...code for auto-populating...}
好,所以我知道了。我在核心数据处理程序中编写了一个函数,用于将所有实体转储到数组中。然后,它遍历数组,拉出所有.name属性。然后,它返回该数组。然后在我的视图控制器中调用该函数并将其设置为等于变量。然后,我将该变量用于UIPickerView数组。下面的代码解决方案。
//function to generate array from core data. This happens in my coreDataManager file.
func fetchSettingName() ->[String] {
let context = persistentContainer.viewContext
var settingOptions = ["none"]
let fetchRequest = NSFetchRequest<Settings>(entityName: "Settings")
do{
let settings = try context.fetch(fetchRequest)
for setting in settings{
settingOptions.append("\(setting.name!)")
}
return settingOptions
}catch let fetchError {
print("Failed to fetch companies: \(fetchError)")
}
return [""]
//How I implemented it into my UIPickerView.This happens in my view controller
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
//calls an array out of core data. The array contains all the title properties for all setting entities
let settingOptions = coreDataManager.shared.fetchPresetsName()
return settingOptions.count