簡體   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