Creating an example for a struct is very easy and straightforward. For example,
import Foundation
struct User: Identifiable, Codable {
let id: UUID
let isActive: Bool
let name: String
let age: Int
let company: String
static let example = User(id: UUID(), isActive: true, name: "Rick Owens", age: 35, company: "Rick Owens Inc.")
}
Now, how can I create an example if I made this an entity in core data? I can’t just put let example = CachedUser(id: UUID(), ...)
like I did with the struct. I want this example to be part of my core data automatically without having to manually create it by using forms, buttons, etc… Thanks in advance!
2
Answers
You can simply check if your default user exists in database. If it does not then you need to create one and save it. Something like the following would work if you have synchronous operations:
This will lazily return existing or generate a new user for you. This user will then be persistent in your database.
The code will only be executed once per session, first time you call
CachedUser.example
.If you have your database setup asynchronous then with closures it should look something like this:
But in this case it makes sense to warmup your application before you show screens that require this user to be present. You can for instance have a loading screen when your app first starts and continue to next screen once this method has finished…
In both cases you now hold a static property to your example entry such as
User.example
which can be used anywhere.But in both cases you may stumble to issue if user (if able to) deletes this entry from database. You would need to handle that case. Either prevent that action or create a new example user once the old one is deleted.
To access this manager put
In a ViewModel or a View
The generic classes that are a part of this code are below. You don’t need them per say it just makes some of the code reusable through the app.
The
previewAware
variable that is mentioned goes with the Apple standard code in thePersistenceController
It automatically give you the
preview
container so you don’t have to worry about adapting your code for samples in Canvas. Just add the below code to thePersistenceController