Chris126
Chris126

Reputation: 35

Swift CoreData: Unrecognised Selector sent to Instance

I am implementing Swift CoreData into my application, However I continue to face the error 'Unrecognised selector sent to Instance' when adding data to the class set up as you can see below. I realise that this is probably a rookie error, so thanks for your patience.

func coreDataRequest(){

    container = NSPersistentContainer(name: "tileData")
    
    container.loadPersistentStores { StoreDescription, error in
        if let error = error {
            print("Unresolved Error \(error)")
        }
    }
    
    var campaign = Campaign()
    campaign.countryName = "France"
}

The Error

unrecognized selector sent to instance

Here is my XCDataModel

Xcode Screenshot

Upvotes: 1

Views: 139

Answers (2)

Nosov Pavel
Nosov Pavel

Reputation: 1571

Have you generate Campaign() class, that you add to tileData.xcdatamodeld? enter image description here

if so create a NSManagedObjectContext like this:

var context: NSManagedObjectContext = {
    return persistentContainer.viewContext
}()

and then use it to create Campaign like this:

var campaign = Campaign(context: context)
campaign.countryName = "France"

then if you want to store your object you have to call save on the context:

func saveContext () {
      if context.hasChanges {
          do {
              try context.save()
          } catch {
            context.rollback()
              let nserror = error as NSError
              fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
          }
      }
  }

I recommend you to look through few tutorials, it would save your time in future. There are a lot of them, just google it.

Upvotes: 2

Wicus Fourie
Wicus Fourie

Reputation: 21

Without seeing all your code its difficult to say what is wrong, just from what I can see the container is missing a "let" in-front unless that was declared outside the function. This is a really good tutorial on setting up and using CoreData https://www.raywenderlich.com/books/core-data-by-tutorials/v7.0/chapters/3-the-core-data-stack#toc-chapter-006-anchor-011

Upvotes: 1

Related Questions