gpt4 book ai didi

ios - 在使用 Swift 3 的 Xcode 8 中寻找有关修订后的 NSPersistentContainer 的清晰教程

转载 作者:可可西里 更新时间:2023-11-01 03:08:44 24 4
gpt4 key购买 nike

我评论过 Apple 的:

Xcode 8 发行说明:
https://developer.apple.com/library/content/releasenotes/DeveloperTools/RN-Xcode/Introduction.html

从 Swift 2.2 迁移到 Swift 2.3 或 Swift 3
https://swift.org/migration-guide/

macOS 10.12、iOS 10.0、tvOS 10.0 和 watchOS 3.0 中核心数据的新增功能
https://developer.apple.com/library/content/releasenotes/General/WhatNewCoreData2016/ReleaseNotes.html#//apple_ref/doc/uid/TP40017342-CH1-DontLinkElementID_1

还有很多其他的...但是应该从 Apple 获得的一份文档,核心数据编程指南,却没有从 Swift 2 更新。
https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CoreData/FetchingObjects.html#//apple_ref/doc/uid/TP40001075-CH6-SW1

理想情况下,我正在寻找类似这样的东西,但对于 Swift 3。
https://www.raywenderlich.com/115695/getting-started-with-core-data-tutorial

任何线索将不胜感激。

根据 Tom 的评论(下方)我缺少哪一步?

1) 创建一个新项目“测试”

2) 选择使用 CoreDate(这会创建 Test.xcdatamodeld)

这将使用以下内容自动填充 AppDelegate(删除默认注释):

func applicationWillTerminate(_ application: UIApplication) {
self.saveContext()
}
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "Test")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}

3) 创建实体“Foo”

4) 添加属性“bar”类型字符串

5) 在 ViewController.swift 下添加以下内容(这是从 Apple 复制的,我只是将“...use”替换为“print”)

func findAnimals() {
let request: NSFetchRequest<Foo> = Foo.fetchRequest
do {
let searchResults = try context.fetch(request)
print(searchResults)
} catch {
print("Error with request: \(error)")
}
}

6) 在 override func viewDidLoad() 下添加 findAnimals()。

但是这有具体的错误:

  1. NSFetchRequest <使用未声明的类型'NSFetchRequest'
  2. 上下文 <使用未解析的标识符“上下文”

7) 所以你返回并在 viewController 下的函数中添加一些东西以使容器可访问(这不是在 Apple 的示例中)。

let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

很好,我们清除了 2 个错误中的 1 个,但错误“使用未声明的类型‘NSFetchRequest’”仍然存在。

这就是我卡住的地方。即使查阅了 Apple 发布的所有 Material ,我也找不到完整的示例。

最佳答案

@Aaron 再次感谢视频链接,它让我走上了正确的轨道。下面是在 Xcode 8 中使用 Swift 3 获取、添加和清除核心数据所需的最低限度的快速演练。

  1. 新项目 > iOS 单 View 应用
  2. 产品名称:“样本”
  3. 使用核心数据(选中)
  4. 保存
  5. 打开 Sample.xcdatamodeld
  6. 添加实体:“SampleEntity”
  7. 使用数据模型检查器将 Codegen(在类下)设置为“类定义”
  8. 在新实体下创建一个属性:“sampleAttribute”
  9. 打开 ViewController.swift
  10. 在“import UIKit”下添加“import CoreData”
  11. 在类 ViewController 下添加以下内容:

    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext// Get data from he attributefunc getSample() {    let request: NSFetchRequest = SampleEntity.fetchRequest()    request.resultType = NSFetchRequestResultType.dictionaryResultType    do {        let searchResults = try context.fetch(request as! NSFetchRequest<NSFetchRequestResult>) as! [NSDictionary]        let searchResultsArray = searchResults.map { $0["sampleAttribute"] as! String}        print("searchResultsArray", searchResultsArray)    } catch {        print("Error with request: \(error)")    }}// Save to the attributefunc setSample() {    let saveSample = SampleEntity(context: context)    saveSample.sampleAttribute = "Save a new string."    do {        try context.save()    } catch {         print("Error with save: \(error)")    }}// clear the attributefunc resetSample() {    let clearSample: NSFetchRequest = SampleEntity.fetchRequest()    let deleteResults = NSBatchDeleteRequest(fetchRequest: clearSample as! NSFetchRequest<NSFetchRequestResult>)    do {        try context.execute(deleteResults)        try context.save()    } catch {        print("Error with save: \(error)")    }}
  12. 在 override func viewDidLoad() 下添加以下内容:

    getSample()setSample()getSample()resetSample()getSample()
  13. 运行,会看到调试区打印如下:

    searchResultsArray []                       // Initially the attribute is emptysearchResultsArray ["Save new string."]     // The attribute now contains the string searchResultsArray []                       // This attribute has been cleared

关于ios - 在使用 Swift 3 的 Xcode 8 中寻找有关修订后的 NSPersistentContainer 的清晰教程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39586084/

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