尝试返回要在PickerView中使用的数据库行

时间:2017-01-28 04:08:20

标签: ios swift core-data

你好我是ios和编程的新手。

我正在尝试使用从核心数据实体加载选项的选择器视图。

不知道该怎么做这是我到目前为止所做的,但是"返回输出[row]"不对。我可以帮忙解决这个问题吗?感谢

//
//  storeSelect.swift
//  assignment2_18094969
//
//  Created by James Duncombe on 25/1/17.
//  Copyright © 2017 James Duncombe. All rights reserved.
//

import UIKit
import CoreData

class storeSelect: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {

    let managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

    //outlet for the pickerview widget
    @IBOutlet weak var picker: UIPickerView!

    var output : [StoreTable] = []

    //var to store the pickerview data (change this to suit the db later)
    //var pickerDataSource = ["Narellan", "Camden", "Campbelltown", "Liverpool", "Parramatta"]; //ignore this atm

    override func viewDidLoad() {
        super.viewDidLoad()


        output = retrieveRows()

        self.picker.dataSource = self
        self.picker.delegate = self

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return output.count;
    }


    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return output[row]
    }

    func retrieveRows() -> [StoreTable]{
        let entityDescription = NSEntityDescription.entity(forEntityName: "StoreTable", in: managedObjectContext)
        let request = NSFetchRequest<NSFetchRequestResult>()
        request.entity = entityDescription // get the table drinkTable
        var storeObjs = [StoreTable]()

        do{
            try storeObjs = managedObjectContext.fetch(request) as! [StoreTable] }
        catch {
            //show some error msg
        }


        return storeObjs;
    }
    //output variable stores PizzaTable data and displays using the retrieve method



    /*
    // 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.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

1 个答案:

答案 0 :(得分:0)

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
   return "abcd"
}

上述函数应返回 String 。不是coredata实体。如果实体 StoreTable 具有String属性,例如我们假设它的名称为String类型,那么该函数应为

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
   return return output[row].name
}