使用Swift使用Core Data对象填充UIPickerView

时间:2015-06-11 03:50:55

标签: ios swift uipickerview

我正在尝试在Swift应用程序中使用Core Data对象填充UIPickerView。

目前,我正在获取一个包含4行的选择器视图(Core Data实体中有4个对象)。我的问题是所有4行标题都来自同一个对象。请看一下截图:

enter image description here

这是我目前的一段代码:

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
}

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

我的代码中缺少什么?

谢谢。

1 个答案:

答案 0 :(得分:2)

好像你总是检索获取结果中的第一个元素:

尝试更改此内容:

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

对此:

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