Looking for a clear guide to the revised NSPersistentContainer in Xcode 8 with Swift 3

I looked at Apple:

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

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

What's new in Core Data on 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 one document that should be available from Apple, Master Data Programming Guide, is not updated with 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 similar, but for Swift 3.
https://www.raywenderlich.com/115695/getting-started-with-core-data-tutorial

Any conclusions would be greatly appreciated.

Comment in Tom Tom (below) What step am I missing?

1) Create a new project "Test"

2) Choose using CoreDate (this creates Test.xcdatamodeld)

This will automatically add AppDelegate to 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 an entity "Foo"

4) Add the attribute "bar" type String

5) In 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 () when overriding func viewDidLoad ().

However, this has errors:

  • NSFetchRequest <Using the undeclared type "NSFetchRequest"
  • context <Using the context of an undefined identifier

7) So, go back and add something to the function under the control of the viewController to make the container accessible (which was not in the form of an Apple example).

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

We discarded 1 of 2 errors, but the error "Use undeclared type NSFetchRequest" remains.

And this is where I am stuck. Even after looking at all of Apple's published materials, I cannot find a complete example.

+8
ios swift3 xcode8 core-data
Sep 20 '16 at 5:07
source share
4 answers

@Aaron Thanks again for the video link that got me on the right track. Below is a quick pass for the minimum minimum required to retrieve, add, and clear kernel data using Swift 3 in Xcode 8.

  • New Project> One-View iOS App
  • Product Name: "Sample"
  • Use master data (verified)
  • Save
  • Open Sample.xcdatamodeld
  • Add and entity: "SampleEntity"
  • Use the data model inspector to set Codegen (under the class) to "Class Definition"
  • Create an attribute under the new object: "sampleAttribute"
  • Open ViewController.swift
  • In the section "import UIKit" add "import CoreData"
  • In the ViewController class, 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)")
         }
     } 
  • When overriding func viewDidLoad (), add the following:

      getSample ()
     setSample ()
     getSample ()
     resetSample ()
     getSample () 
  • Run, and in the debug area you will see the following:

      searchResultsArray [] // Initially the attribute is empty
     searchResultsArray ["Save new string."] // The attribute now contains the string 
     searchResultsArray [] // This attribute has been cleared 
+7
Sep 23 '16 at 3:55
source share

Perhaps this year’s video WWDC What's New in Core Data May Give You Some More.

After about 31:20, it shows the code for NSFetchRequest .

+2
Sep 21 '16 at 16:43
source share

In my opinion, NSPersistentContainer separates the main context and the working context in a simple way. You can simply call container.viewContext for any access to UI level data (old NSMainQueueConcurrencyType) and use container.newBackgroundContext for other data import work (old NSPrivtaeQueueConcurrencyType). And by setting automaticallyMergesChangesFromParent to true for any context, it is equal to the old NSManagedObjectContextDidSaveNotification listening.

Link: http://holko.pl/2016/06/23/core-data/

0
Sep 23 '16 at 19:45
source share

I still can not leave comments. So let me say it here. I believe that these two videos will help you. Stanford Paul Hegarty Great Courses Updated!

https://www.youtube.com/watch?v=ssIpdu73p7A - lecture on CoreData https://www.youtube.com/watch?v=whF63GTaW1w - demonstration of the use of CoreData.

0
May 12 '17 at 16:40
source share



All Articles