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

佐手、 提交于 2019-12-25 01:09:06

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/36383592/swift-unacceptable-type-of-value-for-attribute-when-creating-new-nsentity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!