NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

SOLVED: Initializing a single variable from Core Data in a view

Forums > SwiftUI

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:


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:


But something tells me, I'm doing something completely wrong. Maybe someone has an advice how to do it properly.


When you use CoreData you can't create an instance of an entity with NotArray(). You always need an NSManagedObjectContext where it belongs to. That's why NotArray(context: viewContext) works.

When you want to work on an existing and already created instance you need to fetch the item first and then you can work with the item and the properties of it.

The line NotArray(context: viewContext).someString doesn't make sense because you're creating a new instance of NotArray and unless someString has a default value it will be nil. I'm not even sure if you set a default value for someString in your model the default value is created before the viewContext is saved.

The error you're getting with this line is probably because your viewContext is an EnvironmentObject and you use this line in your init() of the view. In my experience you can't use environment variables in the initializer of a view. But this has nothing to do with Core Data.

Edit2 will never work, see above.

Edit3 is the proper way of doing it (Fetch an existing item or create a new one and work on it, then save the viewContext).

I would suggest you take your time and watch a free tutorial about Core Data:


Hacking with Swift is sponsored by Judo

SPONSORED Let’s face it, SwiftUI previews are limited, slow, and painful. Judo takes a different approach to building visually—think Interface Builder for SwiftUI. Build your interface in a completely visual canvas, then drag and drop into your Xcode project and wire up button clicks to custom code. Download the Mac App and start your free trial today!

Try now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.