我能够从核心数据中获取数据,但是现在我想用游戏名称列创建一个数组,以便可以使用该数组填充选择器视图
import UIKit
import CoreData
class GameViewController: UIViewController, NSFetchedResultsControllerDelegate, UIPickerViewDelegate, UIPickerViewDataSource {
var gameCourse: [String] = [String]()
var frc : NSFetchedResultsController = NSFetchedResultsController<NSFetchRequestResult>()
var pc = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
@IBOutlet weak var inputGameDate: UIDatePicker!
@IBOutlet weak var inputGameCourse: UIPickerView!
func fetchRequest() -> NSFetchRequest<NSFetchRequestResult> {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Course")
let sorter = NSSortDescriptor(key: "coursename", ascending: true)
fetchRequest.sortDescriptors = [sorter]
return fetchRequest
}
func getFRC() -> NSFetchedResultsController<NSFetchRequestResult> {
frc = NSFetchedResultsController(fetchRequest: fetchRequest(), managedObjectContext: pc, sectionNameKeyPath: nil, cacheName: nil)
return frc
}
override func viewDidLoad() {
super.viewDidLoad()
self.inputGameCourse.delegate = self as UIPickerViewDelegate
self.inputGameCourse.dataSource = self as UIPickerViewDataSource
frc = getFRC()
frc.delegate = self
do {
try frc.performFetch()
}
catch {
print (error)
return
}
//self.pickerView.reloadData()
gameCourse = ["Eagle Canyon","Ruimsig"]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Number of columns of data
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
// The number of rows of data
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return gameCourse.count
}
// The data to return fopr the row and component (column) that's being passed in
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return gameCourse[row]
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
答案 0 :(得分:0)
首先,您可能想对Course
个对象运行请求:
func fetchRequest() -> NSFetchRequest<Course> {
let fetchRequest = NSFetchRequest<Course>(entityName: "Course")
let sorter = NSSortDescriptor(key: "coursename", ascending: true)
fetchRequest.sortDescriptors = [sorter]
return fetchRequest
}
然后实际执行请求并从结果中获取名称:
do {
let courses: [Course] = try pc.fetch(fetchRequest())
gameCourse = courses.map(course -> course.coursename)
} catch {
print(error)
return
}
答案 1 :(得分:0)
在您的课程中实现此静态方法(NSManagedObject) 并像Course.sortedCourses
一样使用它tsconfig.json