我想通过这个示例代码 https://www.brandpending.com/2016/01/14/using-core-data-in-a-swift-cocoa-app-to-populate-an-nstableview/其中使用Swift和CoreData来创建表。然而,使用 Swift 3 我无法让它工作。最重要的是,我无法正确更换线路
// set up the NSManagedObjectContext
let appDelegate = NSApplication.sharedApplication().delegate as! AppDelegate
managedContext = appDelegate.managedObjectContext
尽管我发现这个相关问题 https://stackoverflow.com/questions/37956720/how-to-create-managedobjectcontext-using-swift-3-in-xcode-8(然而,这是 iOS 而不是 OS X)。我怎样才能替换产生错误消息的那段代码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'
,这会让我假设你只需要修复你的语法。
iOS 10 中的 Swift 3
核心数据至少需要三件事才能发挥作用:
- 托管对象模型
- 持久存储协调器
- 和托管对象上下文
将这三件事放在一起,您就得到了核心数据堆栈。
当 iOS 10 发布时,引入了一个新对象,称为NS持久化容器 https://developer.apple.com/reference/coredata/nspersistentcontainer?language=objc它封装了核心数据堆栈。
如何创建容器对象有解答here https://stackoverflow.com/questions/37956720/how-to-create-managedobjectcontext-using-swift-3-in-xcode-8.
managedObjectContext
现在是一个名为viewContext
,通过以下方式访问:
let delegate = UIApplication.shared.delegate as! AppDelegate
let managedObjectContext = delegate.persistentContainer.viewContext
一篇有用的文章是核心数据的新变化 https://developer.apple.com/library/prerelease/content/releasenotes/General/WhatNewCoreData2016/ReleaseNotes.html,但如果读起来有点太重了,这个全球开发者大会视频 https://developer.apple.com/videos/play/wwdc2016/242/很好地解释了这个主题。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)