Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

insertNewObjectForEntityForName returns nil

I've been using Core Data since it was released for iOS, but I'm having trouble figuring out what's going on with an insertNewObjectForEntityForName method invocation for one of my entities. When the method is called it simply returns a nil object and does not throw an exception.

Here's the code:

@try {
    self.observation = [NSEntityDescription insertNewObjectForEntityForName:@"Observation" inManagedObjectContext:moc];
    NSLog(@"No exception on insert");
}
    @catch (NSException *exception) {
    NSLog(@"Insert exception - %@", exception.description);
}
NSLog(@"observation: %@", self.observation ? self.observation.description : @"nil");

and here's the output:

2012-10-19 10:16:08.749 Track[63779:c07] No exception on insert
2012-10-19 10:16:08.750 Track[63779:c07] observation: nil

I can perform the insert on all the other entities in my ERD. It's just this one that's mocking (pun intended) me.

like image 317
RM34545 Avatar asked Nov 04 '22 13:11

RM34545


1 Answers

(Xcode 7.2 Swift project) After renaming an entity, my data model got confused and began returning nil objects when performing insertNewObjectForEntityForName. Here are the three things I did to fix this:

  1. I first used @PhillipMills' suggestion:po mainQueueContext.persistentStoreCoordinator?.managedObjectModel and in the output I saw that the "managedObjectClassName" was the old entity/class name with the project prefixed.

    ... NewEntityName = "(< NSEntityDescription: 0x7f9773783440>) name DetectedData, managedObjectClassName MyProject.OldEntityName, ...

  2. To try to resolve this, I deleted and recreated the entity. But this also returned nil objects when inserting. I looked in interface builder and saw that the Class field was blank. I set the class name to resolve this. Xcode Data Model Inspector

  3. At some point during this process the Xcode generated Swift files had a third issue:

missing objc() declaration:

import Foundation
import CoreData

class NewEntityName: NSManagedObject {
    // Insert code here to add functionality to your managed object subclass
}

Fixed Version:

import Foundation
import CoreData

@objc(NewEntityName) //THIS WAS MISSING
class NewEntityName: NSManagedObject {
    // Insert code here to add functionality to your managed object subclass
}
like image 94
awoolf Avatar answered Nov 14 '22 21:11

awoolf