寻找一个清晰的教程修改NSPersistentContainer在Xcode 8与Swift 3 [英] Looking for a clear tutorial on the revised NSPersistentContainer in Xcode 8 with Swift 3

查看:1679
本文介绍了寻找一个清晰的教程修改NSPersistentContainer在Xcode 8与Swift 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已查看过Apple's:



Xcode 8发行说明:

https://developer.apple.com/library/content/releasenotes/DeveloperTools/RN-Xcode/Introduction.html a>



从Swift 2.2迁移到Swift 2.3或Swift 3

https://swift.org/migration-guide/



MacOS 10.12,iOS 10.0中的Core Data的新增功能,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的评论(下面)我失去了什么步骤? / p>

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
如果let error = error as NSError? {
fatalError(未解决的错误\(错误),\(error.userInfo))
}
})
返回容器
} b $ b func saveContext(){
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
let nserror = error as NSError
fatalError(未解决的错误\(nserror),\(nserror.userInfo))
}
}
}

3)创建实体Foo



4)添加属性bartype String



5)在ViewController.swift下添加以下内容(这是从苹果中复制的, print)

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

6)添加findAnimals



但是这里有错误:


  1. NSFetchRequest<使用未声明类型NSFetchRequest

  2. 上下文<使用未解析的标识符上下文

7)因此,您可以返回并添加一些东西给viewController下的函数,

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

伟大的我们清除了2错误中的1,但错误使用未声明类型'NSFetchRequest' 。



这里是我被困的地方。

解决方案

@Aaron再次感谢您的视频链接,让我在正确的轨道。下面是快速浏览,在Xcode 8中使用Swift 3从核心数据中获取,添加和清除所需的最低需求量。


  1. 新项目> iOS单一视图应用程序

  2. 产品名称:示例

  3. 使用核心数据>保存

  4. 打开Sample.xcdatamodeld

  5. 添加和实体:SampleEntity

  6. 使用数据模型

  7. 在新实体下创建属性:sampleAttribute

  8. 打开ViewController.swift
  9. 在import UIKit下添加import CoreData
  10. 在ViewController类下添加以下内容:

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

    //从属性获取数据
    func getSample {
    let request:NSFetchRequest = SampleEntity.fetchRequest()
    request.resultType = NSFetchRequestResultType.dictionaryResultType
    do {
    let searchResults = try context.fetch NSFetchRequest )as! [NSDictionary]
    让searchResultsArray = searchResults.map {$ 0 [sampleAttribute] as! String}
    print(searchResultsArray,searchResultsArray)
    } catch {
    print(Request with request:\(error))
    }
    } b
    $ b //保存到属性
    func setSample(){
    let saveSample = SampleEntity(context:context)
    saveSample.sampleAttribute =保存一个新字符串。
    do {
    try contextsave()
    } catch {
    print(Error with save:\(error))
    }
    }

    //清除属性
    func resetSample(){
    let clearSample:NSFetchRequest = SampleEntity.fetchRequest()
    let deleteResults = NSBatchDeleteRequest(fetchRequest:clearSample as !NSFetchRequest
    do {
    try context.execute(deleteResults)
    try context.save()
    } catch {
    print :\(error))
    }
    }


  11. 在覆盖函数viewDidLoad() / p>

     getSample()
    setSample()
    getSample()
    resetSample()
    getSample pre>

  12. 运行,您将在调试区域看到以下内容:

     searchResultsArray [] //最初属性为空
    searchResultsArray [Save new string。] //该属性现在包含字符串
    searchResultsArray [] //此属性已清除



I've reviewed Apple's:

Xcode 8 Release notes:
https://developer.apple.com/library/content/releasenotes/DeveloperTools/RN-Xcode/Introduction.html

Migrating to Swift 2.3 or Swift 3 from Swift 2.2
https://swift.org/migration-guide/

What's New in Core Data in macOS 10.12, iOS 10.0, tvOS 10.0, and watchOS 3.0
https://developer.apple.com/library/content/releasenotes/General/WhatNewCoreData2016/ReleaseNotes.html#//apple_ref/doc/uid/TP40017342-CH1-DontLinkElementID_1

And many others... but the one document that should be available from Apple, the Core Data Programming Guide, hasn't been updated from Swift 2.
https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CoreData/FetchingObjects.html#//apple_ref/doc/uid/TP40001075-CH6-SW1

Ideally I'm looking for something like this but for Swift 3.
https://www.raywenderlich.com/115695/getting-started-with-core-data-tutorial

Any leads would be very much appreciated.

Per Tom's comment (below) What step am I missing?

1) Create a new project "Test"

2) Select use CoreDate (This creates Test.xcdatamodeld)

This will auto populate AppDelegate with the following (default comments removed):

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) Create entity "Foo"

4) Add Attribute "bar" type String

5) Under ViewController.swift add the following (This was copied from Apple, I just replaced "...use" with "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) Add findAnimals() under override func viewDidLoad().

However this has errors specifically:

  1. NSFetchRequest < Use of undeclared type 'NSFetchRequest'
  2. context < Use of unresolved identifier 'context'

7) So you go back and add something this to the function under the viewController to make the container accessible (which wasn't in the example form Apple).

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

Great we cleared 1 of the 2 error but the error " Use of undeclared type 'NSFetchRequest' " remains.

And here is where I'm stuck. Even after reviewing all of Apple's published materials I am unable to find a complete example.

解决方案

@Aaron Thanks again for the video link, that got me on the right track. Below is quick walk through for the bare minimum needed to fetch, add, and clear from core data with Swift 3 in Xcode 8.

  1. New project > iOS Single view application
  2. Product Name: "Sample"
  3. Use Core Data (checked)
  4. Save
  5. Open Sample.xcdatamodeld
  6. Add and entity: "SampleEntity"
  7. Use the Data Model inspector to set Codegen (under Class) to "Class Definition"
  8. Create an attribute under the new entity: "sampleAttribute"
  9. Open ViewController.swift
  10. Under "import UIKit" add "import CoreData"
  11. Under Class ViewController add the following:

    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    
    // Get data from he attribute
    func 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 attribute
    func setSample() {
        let saveSample = SampleEntity(context: context)
        saveSample.sampleAttribute = "Save a new string."
        do {
            try context.save()
        } catch {
             print("Error with save: \(error)")
        }
    }
    
    // clear the attribute
    func 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. Under override func viewDidLoad() add the following:

    getSample()
    setSample()
    getSample()
    resetSample()
    getSample()

  13. Run and you will see the following printed in the debugging area:

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

这篇关于寻找一个清晰的教程修改NSPersistentContainer在Xcode 8与Swift 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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