icekomo
icekomo

Reputation: 9466

Trying to create a new CoreData Entity var to use later in my app

Right now I have something like this:

var currentStatement = Statement()

Where Statement is an entity in CoreData. It's defined as a class var.

And later I use that var and set it to a fetched Statement entity.

currentStatement = negativeFetchedResultsController.fetchedObjects![indexPath.row]

The way I am creating my currentStatement is throwing an error, it's not a fatal error but I would still like to fix it.

I think this is the code that I want to use to create a Statement entity. I am defining this in the viewDidLoad method. But the issue is because it's defined in the viewDidLoad method it's not available to use anywhere else.

let currentStatement = Statement(context: coreDataStack.managedContext)

If I want to be able to use the currentStatement var how should I define that, as

var currentStatement = Statement()

is not the correct way to do that.

Upvotes: 0

Views: 22

Answers (1)

Tom Harrington
Tom Harrington

Reputation: 70946

You need to declare currentStatement to be an optional. You can't initialize it with Statement() because that doesn't call the designated initializer. But you can't call the designated initializer until you have a managed object context. Making it optional resolves the situation by not requiring you to initialize the variable when the owning object is initialized.

Once you've done that, change the line in viewDidLoad to assign a value to it. Something like

self.currentStatement = Statement(context: coreDataStack.managedContext)

(Note that self. isn't necessary there but can make it clearer).

Upvotes: 1

Related Questions