Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add Core Data to existing Xcode 9 Swift 4 iOS 11 project?

An update is requested, since this question has of course been answered for previous versions, the latest search result dated 12/16 generates irrelevant compatibility with previous iOS 9 and 10 projects.

The documentation of course says to select the Use Core Data checkbox when starting a new project, which I did not select, but now think iCloud + Core Data needs to be added to take my app to its next phase -> wherein something like NSFileCoordinator and NSFilePresenter is needed, since in my app UI users are presented with a number of TOPICS, each having three OPTIONS, regarding which users are to choose one option. For each topic the UI then displays the TOTAL NUMBER of users who have chosen each option and the PERCENTAGE of the total for each option.

Right now, the number of choices for each option and the percentage of the total are of course just calculated in my native app -> but actually need to be CALCULATED in something central like the cloud or most likely on a website…but then the website raises the simultaneous read/write problems that NSFileCoordinator and NSFilePresenter have already solved.

So if the iCloud + Core Data system can interject basic arithmetic calculations on the existing Ubiquitous Container numerical value totals - in the cloud upon receiving write numerical value commands from individual users - before sending out the new Ubiquitous Container numerical total and percent values - then I’d much appreciate advise on how fix the errors generated below in trying Create and Initialize the Core Data Stack. Otherwise guess I’ll have to scrape Xcode and go to a hybrid app like PhoneGap if that's the best one for the job.

Hence, referring to the Core Data Programming Guide:

https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CoreData/InitializingtheCoreDataStack.html#//apple_ref/doc/uid/TP40001075-CH4-SW1

and pasting in the following code in the beginning of my existing project, generates

Use of unresolved identifier ‘persistentContainer’… ‘managedObjectContext’

... errors. And the line

init(completionClosure: @escaping () -> ()) { 

... generates

Initializers may only be declared within a type

import UIKit

import CoreData
class DataController: NSObject {
  var managedObjectContext: NSManagedObjectContext
  init(completionClosure: @escaping () -> ()) {
    persistentContainer = NSPersistentContainer(name: "DataModel")
    persistentContainer.loadPersistentStores() { (description, error) in
      if let error = error {
        fatalError("Failed to load Core Data stack: \(error)")
      }
      completionClosure()
    }
  }
}

init(completionClosure: @escaping () -> ()) {
  //This resource is the same name as your xcdatamodeld contained in your project
  guard let modelURL = Bundle.main.url(forResource: "DataModel", withExtension:"momd") else {
    fatalError("Error loading model from bundle")
  }
  // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
  guard let mom = NSManagedObjectModel(contentsOf: modelURL) else {
    fatalError("Error initializing mom from: \(modelURL)")
  }

  let psc = NSPersistentStoreCoordinator(managedObjectModel: mom)

  managedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.mainQueueConcurrencyType)
  managedObjectContext.persistentStoreCoordinator = psc

  let queue = DispatchQueue.global(qos: DispatchQoS.QoSClass.background)
  queue.async {
    guard let docURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last else {
      fatalError("Unable to resolve document directory")
    }
    let storeURL = docURL.appendingPathComponent("DataModel.sqlite")
    do {
      try psc.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: nil)
      //The callback block is expected to complete the User Interface and therefore should be presented back on the main queue so that the user interface does not need to be concerned with which queue this call is coming from.
      DispatchQueue.main.sync(execute: completionClosure)
    } catch {
      fatalError("Error migrating store: \(error)")
    }
  }
}

// followed by my existing working code:

class ViewController: UIViewController {
like image 240
ehounder Avatar asked Feb 10 '18 18:02

ehounder


People also ask

How do I add Core Data to an existing project in Swift?

Add a Core Data Model to an Existing ProjectChoose File > New > File and select the iOS platform tab. Scroll down to the Core Data section, select Data Model, and click Next. Name your model file, select its group and targets, and click Create.

How do I use Core Data in Xcode?

Open Xcode and create a new iOS project based on the Single View App template. Name the app HitList and make sure Use Core Data is checked. Checking the Use Core Data box will cause Xcode to generate boilerplate code for what's known as an NSPersistentContainer in AppDelegate.


2 Answers

go to File > new file... select core Data under iOS and select Data Model you'll still need some code which xcode auto generates whenever you select core data during project creation. to get it, just create new project with core data option checked and copy all the code written under ** //Mark: - Core Data Stack** comment in AppDelegate.swift and add

import CoreData

above

OPTIONAL

And don't forget to change the name of the app after copying the completion block for lazy var persistentContainer. Change the name of your app on this part *NSPersistentContainer(name: "SHOULD-BE-THE-NAME-OF-YOUR-APP") And managedObjectModel function of the code you just copied**

like image 162
Jay N. Avatar answered Oct 26 '22 05:10

Jay N.


If you're lazy like me, here's all the code you need to copy from the new Core Data project... (why make everyone create a new project?). Change YOUR_APP_NAME_HERE

At the top of your AppDelegate.swift file:

import CoreData

At the bottom of AppDelegate.swift file, before the ending curly bracket:

// MARK: - Core Data stack

func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
        // Saves changes in the application's managed object context before the application terminates.
        self.saveContext()
    }

lazy var persistentContainer: NSPersistentContainer = {
    /*
     The persistent container for the application. This implementation
     creates and returns a container, having loaded the store for the
     application to it. This property is optional since there are legitimate
     error conditions that could cause the creation of the store to fail.
    */
    let container = NSPersistentContainer(name: "YOUR_APP_NAME_HERE")
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

            /*
             Typical reasons for an error here include:
             * The parent directory does not exist, cannot be created, or disallows writing.
             * The persistent store is not accessible, due to permissions or data protection when the device is locked.
             * The device is out of space.
             * The store could not be migrated to the current model version.
             Check the error message to determine what the actual problem was.
             */
            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
    })
    return container
}()

// MARK: - Core Data Saving support

func saveContext () {
    let context = persistentContainer.viewContext
    if context.hasChanges {
        do {
            try context.save()
        } catch {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            let nserror = error as NSError
            fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
        }
    }
}
like image 39
iOSDevSF Avatar answered Oct 26 '22 03:10

iOSDevSF