'Bundle.main does not find file in folder structure

Overview

I want to find my core data model as part of the initialisation of NSPersistentContainers (local and cloud) to make sure that they share the same model.

Code

The code I planned to use to achieve this:

static let model: NSManagedObjectModel = {
    guard let url = Bundle.main.url(forResource: "BookKeeping", withExtension: "momd") else {
        fatalError("Failed to locate model file.")
    }
    
    guard let managedObjectModel = NSManagedObjectModel(contentsOf: url) else {
        fatalError("Failed to load model file.")
    }
    
    return managedObjectModel
}()

However this does not do trick, as it fails with the first fatalError "Failed to locate model file".

I presume it has something to do with my folder structure, which is the following:

Folder Structure

In "Persistence" the initialisation takes places, "BookKeeping" is the name of the model file.

Approaches so far

I tried to add the file as Bundle Resource in the Build Phase, I checked that the target membership of the file is right, FileManager is in my opinion not the right approach to get it done and I looked into Bundle identifiers, however it seems to me they are used in different use cases.

If you could put me in the right direction I'd be happy. Any help is greatly appreciated! Thanks!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source