swiftexc-bad-accessnsentitydescription

Swift: Unacceptable type of value for attribute when creating new NSEntity


I have a Core Data entity set up with the following attributes:

resellerNo:Int
resellerName:String

I have setup an NSManagedObject as follows:

class Reseller: NSManagedObject
{
    @NSManaged var resellerNo: Int
    @NSManaged var resellerName: String
}

If I try to run this method:

func createNewReseller(resellerName: String)
{
    let context = app.managedObjectContext

    let resellerEntity = NSEntityDescription.entityForName("Resellers", inManagedObjectContext: context)
    let newReseller = Reseller(entity: resellerEntity!, insertIntoManagedObjectContext: context)

    newReseller.resellerNo = 12
    newReseller.resellerName = resellerName
    saveDatabase()
    Swift.print ("Reseller \(resellerName) created")
}

then it crashes when trying to allocate the resellerNo with an error message:

Unacceptable type of value for attribute: property = "resellerNo"; desired type = NSNumber; given type = __NSTaggedDate; value = 2001-01-01 00:00:00 +0000.

Strange thing is, if you use the console to print newReseller.resellerNo just beforehand then it works fine.

Other code accessing other Entities in exactly the same way work fine.

Any ideas?


Solution

  • OK it turned out to be fairly simple in the end. It turns out I had not added a class to the Entity.

    If your having this problem:

    1. Click on the xcdatamodel
    2. Choose the entity.
    3. Show the Data Model Inspector in the Utilities bar.
    4. Enter the class name defined (in my case Reseller)

    I also had to change my class definition to this:

    @objc(Reseller)
    class Reseller: NSManagedObject
    {
        @NSManaged var resellerNo: Int
        @NSManaged var resellerName: String
    }
    

    Hope this helps someone.