Swift 3中的managedObjectContext [英] managedObjectContext in Swift 3

查看:167
本文介绍了Swift 3中的managedObjectContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过

I want to work through this example code in which Swift and CoreData is used to create a table. However, using Swift 3 I fail to get it to work. Most importantly, I cannot properly replace the line

// set up the NSManagedObjectContext
  let appDelegate = NSApplication.sharedApplication().delegate as! AppDelegate
  managedContext = appDelegate.managedObjectContext

即使我发现了这个相关问题(但是不是iOS,而是OS X).如何替换产生错误消息Value of type 'AppDelegate' has no member 'managedContext'的那段代码?

even though I found this related question (which however is iOS not OS X). How can I replace that piece of code which produces the error message Value of type 'AppDelegate' has no member 'managedContext'?

推荐答案

在macOS中为Swift 3

let appDelegate = NSApplication.shared().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext

您提供的错误是'AppDelegate' has no member 'managedContext'而不是'AppDelegate' has no member 'managedObjectContext',这使我假设您只需要修复语法.

The error you provided says 'AppDelegate' has no member 'managedContext' instead of 'AppDelegate' has no member 'managedObjectContext', which would lead me to assume you just need to fix your syntax.

iOS 10中的Swift 3

核心数据至少需要三件事才能工作:

Core Data needs at least 3 things to work:

  1. 管理对象模型
  2. 持久性存储协调员
  3. 还有一个托管对象上下文
  1. A managed object model
  2. A persistent store coordinator
  3. And a managed object context

将这三件事放在一起,您将获得核心数据栈.

Put those three things together and you get the Core Data Stack.

iOS 10发布时,引入了一个新对象,称为 NSPersistentContainer 封装了核心数据栈.

When iOS 10 came out, a new object was introduced called the NSPersistentContainer which encapsulates the core data stack.

此处回答了如何创建容器对象.

managedObjectContext现在是一个名为viewContext的属性,可以通过以下方式访问:

managedObjectContext is now a property called viewContext, accessed via:

let delegate = UIApplication.shared.delegate as! AppDelegate
let managedObjectContext = delegate.persistentContainer.viewContext

有用的文章是核心数据中的新功能,但如果该读数似乎太重了,请 WWDC视频 WWDC视频在解释这个主题方面做得很出色.

A helpful article is What's New in Core Data, but if that reading seems a little too heavy, this WWDC video does a great job of explaining this topic.

这篇关于Swift 3中的managedObjectContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆