BLACK FRIDAY SALE: Save big on all my Swift books and bundles! >>

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:

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.

   

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: https://www.youtube.com/watch?v=6XASUd7h5-s&list=PLMRqhzcHGw1aDYKmCuqXQ_IqpWpJlpoJ3

1      

Hacking with Swift is sponsored by RevenueCat

SPONSORED In-app subscriptions are a pain to implement, hard to test, and full of edge cases. RevenueCat makes it straightforward and reliable so you can get back to building your app. Oh, and it's free if your app makes less than $10k/mo.

Learn more

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

Reply to this topic…

You need to create an account or log in to reply.

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.