第二个视图中的 AppDelegate 声明

AppDelegate declaration in a second view

我的应用程序有问题,可能无法管理 AppDelegate。 我有 2 个视图,一个是主视图,第二个是设置视图。 我的第一个视图将访问我的核心数据(字符串中的 7 个 IP 地址)。当转到第二个视图时,我想将 IP 地址修改到我的 CoreData 中。 我当然可以在我的第一个视图中访问我的数据,并且我正在发送(segue)到我的第二个视图。 我的问题是,我想从第二个视图更改我的 IP 地址并将其保存到我的核心数据中。 我知道如何保存,....但是,我需要创建一个 ManagedObject,为此我需要一个 AppDelegate。 但是,我的 AppDelegate 声明似乎不起作用。我的意思是,Xcode 告诉我 AppDelegate 未声明。

我可以将我的 AppDelegate 从第一个视图切换到第二个视图吗? 要么 如何在我的 SecondView 中创建一个 AppDelegate?

在此先感谢您的帮助和支持。

如果我没理解错的话,您想从另一个 ViewController 访问您的应用委托?

就这样:

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

根据 Wain 的建议,最佳做法是让主视图控制器将托管对象上下文传递给设置视图控制器。

这称为依赖注入,下面是您如何通过 segue 来实现:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "showSettings" {
        if let destinationVC = segue.destinationViewController as? SettingsViewController{
            // Pass our managed object context to the settings controller
            destinationVC.managedObjectContext = managedObjectContext
        }
    }
}

您可以将 managedObjectContext 属性 添加到您的设置视图控制器,如下所示:

import CoreData

class SettingsViewController: UIViewController {

    var managedObjectContext : NSManagedObjectContext?

依赖注入的好处是每个视图控制器只使用给它的上下文,而不是寻找一个"known"地方(比如AppDelegate)来获取全局管理对象上下文.

这消除了视图控制器与 AppDelegate 之间的紧密耦合,还使您可以灵活地在整个应用程序中使用多个 NSManagedObjectContext,随着项目规模的扩大,这一点通常变得很重要和复杂性。

Apple 在其 Accessing the Core Data Stack 文档中推荐了这种做法:

When you create a view controller, you pass it the context it should use. You pass an existing context, or (in a situation where you want the new controller to manage a discrete set of edits) a new context that you create for it. It’s typically the responsibility of the application delegate to create a context to pass to the first view controller that’s displayed.

A view controller typically shouldn’t retrieve the context from a global object such as the application delegate—this makes the application architecture rigid.

更新:

在回答您关于如何创建 NSManagedObject 的评论时,您只需要一个 NSManagedObjectContext,您的第二个视图控制器现在已经有了。

let employee = NSEntityDescription.insertNewObjectForEntityForName("Employee", inManagedObjectContext: self.managedObjectContext) as! Employee

有关详细信息,请参阅 Apple 核心数据编程指南 中的 Creating and Saving Managed Objects

None 你的视图控制器应该需要访问 AppDelegate,因为你现在正在传递一个上下文供他们使用。