iosipadcore-dataswiftnsentitydescription

NSEntityDescription returns nil on iPad Air 7.1 only


I have been working with CoreData recently for an app of mine. Oddly enough it is crashing only on the iPad Air with iOS 7.x. I have run in both on physical devices and the iOS simulator, it never fails to crash on the Air, and always runs elsewhere. (It does not crash on the iPad Air iOS 8.0)

The crash is happening in one of my CoreData calls, specifically

    var childEntity = NSEntityDescription.entityForName(ChildInSessionEntity, inManagedObjectContext: context)
    var parentEntity = NSEntityDescription.entityForName(ParentInSessionEntity, inManagedObjectContext: context)
    var newChild = ChildInSession(entity: childEntity, insertIntoManagedObjectContext: context)
    var newParent = ParentInSession(entity: parentEntity, insertIntoManagedObjectContext: context)

The first line does not return nil, but the 2nd line does, and on the 4th line my app crashes.

It is a very odd scenario as on other simulators it does not return a nil value.

Any help or suggestions are greatly appreciated


Solution

  • I think I had the same issue as you. I found that it would crash when accessing an entity for the second time. I was able to fix the issue thanks to this article: http://stackanswers.com/questions/24440927/swift-core-data-on-ios7-device-entityforname-on-second-entity-is-nil

    For some reason, you need pass the entity name as an instance of NSString, e.g.

    // Rather than...
    let entity = NSEntityDescription.entityForName("Entity", inManagedObjectContext: self.managedObjectContext!)
    
    // Use this instead...
    let entityName: NSString = "Entity"
    let entity = NSEntityDescription.entityForName(entityName, inManagedObjectContext: self.managedObjectContext!)
    

    If you're using a fetch request then you can use the shortcut:

    let entityName: NSString = "Entity"
    let fetchRequest = NSFetchRequest(entityName)