繁体   English   中英

将一个ViewController中的managedObjectContext传递给Swift中的另一个ViewController?

[英]Passing an managedObjectContext from one ViewController to another ViewController in Swift?

我当前的项目是Swift中的一个核心数据项目,用于创建笔记。 我正在尝试从prepareForSeguecurrentVC设置我的destinationVC的managedObjectContext,我试图弄清楚如何在Swift中做到这一点。

我使用Apple的“固定代码”在Swift中设置CoreData项目。 CoreData堆栈在AppDelegate.swift设置。

目前,如果托管对象上下文中没有注释,我创建了一种在AppDelegate中生成虚拟注释的方法。 这样可行。

应用程序打开时的初始视图是Master-Detail VC设置,用于显示托管对象上下文中的对象。 这样可行。 我可以单击一个注释,它将显示在DetailViewController上。 这主要是Xcode在我启动项目时创建的“预制”代码。

我在MasterViewController上创建了一个UIBarButtonItem “Add”按钮,但我无法弄清楚如何将MasterVCmanagedObjectContext传递给destinationViewController 当我点击它它应该细分到DetailViewController

以下是我的MasterVC的属性:

var detailViewController: DetailViewController? = nil
var addNoteViewController:AddNoteViewController? = nil  // I added this
var managedObjectContext: NSManagedObjectContext? = nil

这是我在MasterViewController prepareForSegue方法。

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "showDetail" {
        if let indexPath = self.tableView.indexPathForSelectedRow() {
            let object = self.fetchedResultsController.objectAtIndexPath(indexPath) as! NSManagedObject
            let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController
            controller.detailItem = object
            controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem()
            controller.navigationItem.leftItemsSupplementBackButton = true
        }
    }

    if segue.identifier == "addNote" {
        println("segue.identifier is addNote")
        // I think I need to add stuff here so the destination VC "sees" the managedObjectContext
    }
}

我想我还需要在AddNoteVC上添加一个MasterVCprepareForSegue可以设置的属性。 那么我如何在Swift中做到这一点?

要向AddNoteViewController添加属性,只需添加一个var

import CoreData

class AddNoteViewController: UIViewController {

    var managedObjectContext : NSManagedObjectContext?

然后你可以在你的segue中设置这个属性:

if segue.identifier == "addNote" {
    println("segue.identifier is addNote")
    // I think I need to add stuff here so the destination VC "sees" the managedObjectContext

    let controller = (segue.destinationViewController as! UINavigationController).topViewController as! AddNoteViewController
    controller.managedObjectContext = managedObjectContext
}

谜团已揭开:

我将这行代码添加到AddNoteViewController ,在MasterViewController.swift中的prepareForSegue中没有任何内容

let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM