gpt4 book ai didi

ios - UIApplicationDelegate 在 Swift 应用程序中没有名为 managedObjectContext 的成员

转载 作者:搜寻专家 更新时间:2023-11-01 05:54:28 25 4
gpt4 key购买 nike

我想在我的 Swift iOS 应用程序中使用 Core Data,但如何从任何 ViewController 中调用 Core Data 的 managedObjectContext?

假设我想调用这个在 Objective-C 中经常使用的方法:

self.managedObjectContext = ((AppDelegate *) [UIApplication sharedApplication].delegate).managedObjectContext;

但是,当我在我的 Swift 文件中编写以下代码时,出现了错误:UIApplicationDelegate does not have a member called managedObjectContext

var appDelegate = UIApplication.sharedApplication().delegate
println(appDelegate.managedObjectContext)

为什么会出现这个错误?因为我在创建应用程序时检查了 Core Data,模板自动在 AppDelegate.swift 文件中定义了 managedObjectContext 变量。

那么缺少什么?我使用 Xcode 6 beta 5。

最佳答案

您需要将应用委托(delegate)转换为项目的应用委托(delegate)类型。

let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let context = appDelegate.managedObjectContext

关于ios - UIApplicationDelegate 在 Swift 应用程序中没有名为 managedObjectContext 的成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25333115/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com