How to initialize the created main NSManagedObject file in Swift

I know obj-c, but I learn fast.

In obj-c, when using master data, you model your data and specify xcode to subclass your model's nsmanageobject. Then in the code you initialize it as

#import MyObject - (void) someMethod { MyObject *my = (Card *) [NSEntityDescription insertNewObjectForEntityForName:@"Card" inManagedObjectContext:[self managedObjectContext]]; my.name = @"some name"; } 

In swift, I am trying to do the same, but I cannot figure out how to initialize my custom object. This is what I have:

Subclass NSManagedObject created:

import Foundation import CoreData p>

 class Card: NSManagedObject { @NSManaged var card_name: String @NSManaged var card_id: String @NSManaged var card_issuer: String @NSManaged var card_type: String } 

Then I try to use it in another class, for example:

 var card : Card card.card_name = "Some Name" card.card_issuer = "HOA" card.card_type = "Rec Center" card.card_id = "123" 

But I get the error:

Map variable used before initialization

I clearly lack a step, but I can’t indicate what it is.

In addition, as mentioned by several iOS instructors, you should not interact with the created NSManagedObject subclass.

Any suggestions?

Edit I get an error: (probably there should be a new SO question ...)

CoreData: warning: Unable to load class with name 'Card' for entity 'Card'. The class was not found, using the default NSManagedObject instead.

Here are screenshots showing how this class exists in the build phase and the object name was set in the xcdatamodeld file enter image description here

enter image description here Thanks

+5
source share
2 answers

Do you have that:

 var card : Card 

This means that card is of type card , but does not instantiate. Before use, you must select and initialize the instance. The initialization rule here is the same as in Objective-C, i.e. You must call the designated initializer for the object. You would do something like this:

 var card = NSEntityDescription.insertNewObjectForEntityForName("Card", inManagedObjectContext: self.managedObjectContext) as! Card 

In this case, your Objective-C snippet is incorrect because init not a designated initializer for NSManagedObject .

+8
source

You declare a variable card , but you never initialize it.

You will need a Core Data context, and then you can create an instance:

 let entity = NSEntityDescription.entityForName("Card", inManagedObjectContext: managedObjectContext) let card = Card(entity: entity!, insertIntoManagedObjectContext: managedObjectContext) 

In this context, an empty card instance will be created. When you save the context, your new map will be in the store.

+1
source

Source: https://habr.com/ru/post/1216201/


All Articles