Hey, everyone! Some pathetic issue, as usual.
I understood how to work with @FetchRequest
property wrapper and how to create and save arrays in Views, but when it comes to single values I've got an issue.
I create a project (default XCode project, with check a "Use Core Data" checkmark). It has a xcdatamodeld with "Item" entity and example 10 cells list with dates. An object was created in enviroment as viewContext and Item is FetchRequested.
I create another Entity in Core Data, called NotArray
. I want to store single variables, not arrays. I create two attributes: someInt
(Int16) and someSting
(String).
Then, in my ContentView I'm trying to let a = NotArray(context: viewContext).someString
, and code refuses to build, because:
Cannot use instance member 'viewContext' within property initializer; property initializers run before 'self' is available.
Please, help! I really can't understand what exactly does it mean.
EDIT: For a sake of experiment, I've added to my Persistence file some example data:
let notArray = NotArray(context: viewContext)
notArray.someInt = 25
notArray.someString = "Some String"
But still, cannot even see them in my view.
EDIT2: If I directly push it to some visual controller like Text:
Text(NotArray().someString!)
It builds, but crashes preview simulator with a execution error of
Thread 1: "-[NotArray someString]: unrecognized selector sent to instance 0x6000016c5680"
EDIT3: I finally managed to extract the value, fetching NotArray with FetchRequest and then displaying the last value:
Text(String(notArray.last!.someString!))
But something tells me, I'm doing something completely wrong. Maybe someone has an advice how to do it properly.