tobhae_dev
tobhae_dev

Reputation: 364

Should Core Data Stack inherit from NSObject and why?

Recently it is practice to move the core data stack implementation from the app delegate to a different class. In most implementations I see that the core data stack inherits from NSObject, even in Apple's documentation.

  1. Is there a reason for that? It seems to work without it.
  2. Why is Apple's init method not calling super.init() isn't it a must have?

import UIKit
import CoreData

class DataController: NSObject {
    var managedObjectContext: NSManagedObjectContext
    init() {
        // This resource is the same name as your xcdatamodeld contained in your project.
        guard let modelURL = NSBundle.mainBundle().URLForResource("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(contentsOfURL: modelURL) else {
            fatalError("Error initializing mom from: \(modelURL)")
        }
        let psc = NSPersistentStoreCoordinator(managedObjectModel: mom)
        managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
        managedObjectContext.persistentStoreCoordinator = psc
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
            let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
            let docURL = urls[urls.endIndex-1]
            /* The directory the application uses to store the Core Data store file.
             This code uses a file named "DataModel.sqlite" in the application's documents directory.
             */
            let storeURL = docURL.URLByAppendingPathComponent("DataModel.sqlite")
            do {
                try psc.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: nil)
            } catch {
                fatalError("Error migrating store: \(error)")
            }
        }
    }
}

Initializing the Core Data Stack

Upvotes: 0

Views: 157

Answers (1)

matt
matt

Reputation: 535222

The stack can live in any object in theory, and in Swift that object need not derive from NSObject. But in reality it also needs to be a singleton globally available to all code, and the demands of Occam's Razor and time will always make the app delegate an obvious locus, since it meets that description perfectly, and especially if that's where it is when you make a new project from the Core Data templates.

Why is Apple's init method not calling super.init() isn't it a must have?

It is done automatically by Swift itself.

Upvotes: 2

Related Questions