user2414590 user2414590 - 1 month ago 23
Swift Question

NSFetchRequest as entityName gives error "use of undeclared type"

I'm using Core data with Swift 2.1 and Xcode 7.2
This code gives me an error that can't find the entity name.This as [Company] doesn't work.I have a entity with this name.

let fetchRequest = NSFetchRequest(entityName: "Company")

do {
var result = try self.moc.executeFetchRequest(fetchRequest) as! [Company]
if (result.count > 0){

companyName?.stringValue = result[0].valueForKeyPath("name") as! String

// success ...
}
else{

}
} catch let error as NSError {
// failure
print("Fetch failed: \(error.localizedDescription)")
}

Answer

You said you have an entity named "Company" in your model. Okay, but do you have an actual NSManagedObject class named Company (ie, class Company: NSManagedObject { ... }) that you created from within the managed object model editor in Xcode? This isn't automatic. Without an actual class declared somewhere, it will be an "undefined type" since the entity name is just a string to look things up in your model otherwise.

The fact the rest of your code is accessing properties by valueForKeyPath() strongly suggests there's no actual class Company: NSManagedObject anywhere.