I'm using CoreData for storage. After following this article and some other additional documentation, I can't seem to overcome NSPersistentContainer
returning nil
.
import CoreData
public class ContactStore {
private lazy var persistentContainer: NSPersistentContainer = {
// !! The problem will be here
let persistentContainer = NSPersistentContainer(
name: "PersistentContact"
)
// Load the persistent store
persistentContainer.loadPersistentStores { description, error in
if let error = error {
fatalError("Couldn't load") // TODO
}
}
return persistentContainer
}()
private lazy var entityDescription: NSEntityDescription? = {
let entityDescription: NSEntityDescription? = NSEntityDescription.entity(
forEntityName: "PersistentContact",
in: self.persistentContainer.viewContext
)
return entityDescription
}()
public init() {
}
static var id: Int64 = 0
private func idAndIncrement() -> Int64 {
let rv:Int64 = ContactStore.id
// TODO: use persistence
ContactStore.id += 1
return rv
}
public func push(contact: Contact) -> NSManagedObject {
let persistentContact = NSManagedObject(
entity: self.entityDescription!,
insertInto: self.persistentContainer.viewContext
)
// contact.id is not used
persistentContact.setValue(contact.distance, forKey: "distance")
persistentContact.setValue(contact.duration, forKey: "duration")
do {
try self.persistentContainer.viewContext.save()
} catch {
fatalError("Something here")
// TODO: failed saving
}
return persistentContact
}
public func pop() -> Contact? {
return nil // TODO
}
}
Then I test it:
class ContactStoreTests: XCTestCase {
func testCreation() {
// Populate with random values
let contact = Contact(
id: "83A8E3C1-3C95-4F0F-9F50-D58E4E1F66F4",
duration: 8.2,
distance: 1,
)
let contactStore: ContactStore = ContactStore()
contactStore.push(contact: contact)
}
}
When I run the tests everything builds fine, but I get the error:
+entityForName: nil is not a legal NSManagedObjectContext parameter searching for entity name 'PersistentContact' (NSInvalidArgumentException)
If I stop the test with a breakpoint after persistentContainer
is initialized, this is what I get:
So it is, in fact, nil. What am I missing?