Create a fake NSManagedObjectContext for preview purposes?

502 Views Asked by At

I want a "fake" preview NSManagedObject to display as an example. However, I don't want to have it cluttering up my regular context. Here's what I'm assuming could work:

  • Create a new NSManagedObjectContext and store the preview NSManagedObject there

    let moc = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
    let person = Person(moc, "Person Name")
    

    What happens to the new context in this case? Is it slowly filling up storage or will it get removed if no save() is called and the View removed?

  • Remove the newly created NSManagedObject when leaving the view

     SomeView()
     .onDisappear() {
         moc.delete(person)
         PersistenceController.shared.save()
     }
    

    This might not work if the .onDisappear() function doesn't get called, e.g. when the user leaves the app while that particular view is still open.

  • Add the fake preview NSMangagedObject to the regular context and filter it out everywhere else (probably the worst idea)

  • Create a new global context only for fake NSManagedObjects

Not sure which of these options is best or if there's a better way I haven't thought of. Thanks :)

1

There are 1 best solutions below

1
fer0n On

I created a new PersistenceController in memory as Joakim Danielson suggested in the comments, but using it alongside my other context was causing crashes and error messages. Simply creating a new NSManagedObjectContext, however, worked fine.

It is not saved to my "real" context, either (Apple Documentation):

Changes to managed objects are held in memory, in the associated context, until that context is saved to one or more persistent stores

let tempMoc = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)

Usage

let person = Person(tempMoc, "Person Name")