Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Core Data on IOS7 device -> entityForName on second entity is nil


i've tested swift on a little iPhone project using Xcode 6 beta 2. The project uses core data to access 2 entities (User/Contract) in a data model. Inside the IOS Simulator everything works fine.

Problem: When i build the app for IOS7 and test the app on my iPhone5s (running IOS 7.1.1) the program can only save data into the first entity (as defined in core data model = User). For all other entities the NSEntityDescription.entityForName(...) is "nil". In managedObjectModel (println(managedObjectModel)) all entities are included. Seems like the data model is not correct included into the SQL-Database on IOS7?! Does anyone have a solution/idea? Thanks :-)

    var myAppDel:AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
    var myContext:NSManagedObjectContext = myAppDel.managedObjectContext

    println(NSEntityDescription.entityForName("User", inManagedObjectContext: myContext))
    println(NSEntityDescription.entityForName("Contract", inManagedObjectContext: myContext)) 

    var newContract:AnyObject = NSEntityDescription.insertNewObjectForEntityForName("Contract", inManagedObjectContext: myContext)

    newContract.setValue("" + txtContract.text, forKey: "contractName")
    myContext.save(nil)

    var newUser = NSEntityDescription.insertNewObjectForEntityForName("User", inManagedObjectContext: myContext)

    newUser.setValue("" + txtUsername.text, forKey: "userName")
    newUser.setValue("" + txtPassword.text, forKey: "userPass")
    newUser.setValue(newContract, forKey: "contracts") // Save Relationship

    myContext.save(nil)

Error: Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '+entityForName: could not locate an entity named 'Contract' in this model.'

like image 507
user3781019 Avatar asked Dec 12 '22 05:12

user3781019


1 Answers

It seems to be a bug for now. As explained on this post: https://devforums.apple.com/message/996259#996259.

The workaround for this bug is to use a NSString instead of passing a String as the entity name:

    let myEntity: NSString = "EntityName"
    var fetchRequest = NSFetchRequest(entityName: myEntity)
like image 194
babzich Avatar answered Jan 26 '23 00:01

babzich