Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include NSPersistentContainer in AppDelegate

I'm receiving an error:

AppDelegate has no member persistentContainer

import UIKit
import CoreData

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        let context = appDelegate.persistentContainer.viewContext // Error: value of type 'AppDelegate' has no member 'persistentContainer'
    }

}

In AppDelegate.swift file, NSPersistentStoreCoordinator is defined as default.

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
    let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
    let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
    var failureReason = "There was an error creating or loading the application's saved data."
    do {
        try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
    }
    catch {
        var dict = [String: AnyObject]()
        dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
        dict[NSLocalizedFailureReasonErrorKey] = failureReason
        dict[NSUnderlyingErrorKey] = error as NSError
        let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
        NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
        abort()
    }
    return coordinator
}()
like image 336
Karthikeyan Sk Avatar asked Dec 20 '16 13:12

Karthikeyan Sk


People also ask

What is NSPersistentContainer?

NSPersistentContainer simplifies the creation and management of the Core Data stack by handling the creation of the managed object model ( NSManagedObjectModel ), persistent store coordinator ( NSPersistentStoreCoordinator ), and the managed object context ( NSManagedObjectContext ).

What is an app delegate?

So an app delegate is an object that the application object can use to do certain things like display the first window or view when the app starts up, handle outside notifications or save data when the app goes into the background.


1 Answers

You should firstly import CoreData framework and then write this code in AppDelegate.swift:

lazy var persistentContainer: NSPersistentContainer = {

    let container = NSPersistentContainer(name: "Your Model File Name")
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error {

            fatalError("Unresolved error, \((error as NSError).userInfo)")
        }
    })
    return container
}()

And then you should write this:

 let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
like image 131
Pragnesh Vitthani Avatar answered Nov 16 '22 17:11

Pragnesh Vitthani