如何将核心数据信息从表视图传递到视图控制器?

时间:2015-01-13 17:16:49

标签: ios swift core-data

我的应用程序有一个UITableView,显示有关项目的简短数据,我正在尝试将用户按下单元格时将其发送到另一个viewController。那个viewController被命名为detailViewController,我想让它显示有关所选单元格的更多细节。我正在使用核心数据,我的问题就在这里。我不知道如何将存储在cordite中的一个特定对象传递给另一个视图控制器。这是我的代码:

var tasks: Array<AnyObject> = [] //Creating an array that will store fetched data

override func viewWillAppear(animated: Bool) {

let appDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let contexts: NSManagedObjectContext = appDel.managedObjectContext!
let fetchreq = NSFetchRequest(entityName: "toDo")

tasks = contexts.executeFetchRequest(fetchreq, error: nil)!
tableView.reloadData()

}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {


let CellID: NSString = "myCell"

var cell: CustomCell = tableView.dequeueReusableCellWithIdentifier(CellID) as CustomCell

if let indexpth = indexPath as NSIndexPath! {

    var data: NSManagedObject = tasks[indexpth.row] as NSManagedObject
    cell.theTextLabel?.text = data.valueForKeyPath("toDoName") as? String

    cell.theDetailTextLabel?.text = data.valueForKeyPath("toDoNumber") as? String

}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.

    if segue.identifier == "showDetail" {

        var detailVC: DetailViewController = segue.destinationViewController as DetailViewController

        var index: NSIndexPath = self.tableView.indexPathForSelectedRow()!
        var row: NSInteger = index.row

        var myData: NSManagedObject = tasks[row] as NSManagedObject

        var tName: AnyObject? = testData.valueForKeyPath("tName")
        detailVC.detailTasks = myData
        detailVC.detailName = tName

    }

}

我不确定如何将存储在核心数据中的对象传递给另一个视图控制器,我尝试了很多东西,但似乎没有用。谢谢你们!

2 个答案:

答案 0 :(得分:1)

我在尝试了几件事后解决了我的问题,下面的代码对我有用。在我的DetailViewController中,我将标签从标签更改为文本字段以显示信息。我创建了一个类型为string的变量detailName,并将我的数据放在那里。谢谢你们帮助你们!

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {


    if segue.identifier == "showDetail" {

        var detailVC: DetailViewController = segue.destinationViewController as DetailViewController

        var selectedItem: NSManagedObject = tasks[self.tableView.indexPathForSelectedRow()!.row] as NSManagedObject

        detailVC.detailName = selectedItem.valueForKey("tName") as String

    }

答案 1 :(得分:0)

检查以确保在传递任何数据之前已分配并初始化了detailVC。我猜这是个问题。