使用 Swift 使用核心数据 objects 填充 UIPickerView

Populating UIPickerView with Core Data objects using Swift

我正在尝试在 Swift 应用程序中使用核心数据 object 填充 UIPickerView。

目前,我得到一个包含 4 行的选择器视图(核心数据实体中有 4 objects)。我的问题是所有 4 行标题都来自同一个 object。请看截图:

这是我当前的代码:

override func viewWillAppear(animated: Bool) {
    
    getFetchedResultController_cat(currentEntity_cat)
}


func getFetchedResultController_cat(selectedEntity: NSString){
    
    let appDelegate : AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let managedObjectContext: NSManagedObjectContext = appDelegate.managedObjectContext!
    
    let fetchRequest = NSFetchRequest()
    
    let entity = NSEntityDescription.entityForName(selectedEntity as String, inManagedObjectContext: managedObjectContext)
    
    fetchRequest.entity = entity
    
    fetchRequest.fetchBatchSize = 20
 
    let sectionSortDescriptor = NSSortDescriptor(key: "name", ascending: true)
    
    let sortDescriptors = [sectionSortDescriptor] //, secondSortDescriptor]
    
    fetchRequest.sortDescriptors = sortDescriptors
    
    let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: managedObjectContext, sectionNameKeyPath: nil, cacheName: nil)
    
    aFetchedResultsController.delegate = self
    self.fetchedResultsController_cat = aFetchedResultsController
    
    var error: NSError? = nil
    if !self.fetchedResultsController_cat.performFetch(&error) {
        abort()
    }
    let x : Int = (self.fetchedResultsController_cat.fetchedObjects?.count ?? 0)
    println("CATEGORIAS ACTUALES=")
    println(x)
    self.pickerView.reloadAllComponents()
}

func pickerView(pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
    return 100
}
//size the components of the UIPickerView
func pickerView(pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
    return 20.0
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
    return 1
}

func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return fetchedResultsController_cat.fetchedObjects?.count ?? 0
}

func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
  
    let indexPath = NSIndexPath(forRow: 0, inSection: 0)
    let fetchedObject: AnyObject = self.fetchedResultsController_cat.objectAtIndexPath(indexPath)
    print (fetchedObject.valueForKey("name"))
    var nombre: AnyObject? = fetchedObject.valueForKey("name")
    return nombre as! String
}

我想在每一行显示正确的行标题。

我的代码中缺少什么?

谢谢。

您似乎总是在检索获取结果中的第一个元素:

尝试改变这个:

let indexPath = NSIndexPath(forRow: 0, inSection: 0) 

为此:

let indexPath = NSIndexPath(forRow: row, inSection: 0)