user2414590
user2414590

Reputation: 123

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)")
    }

Upvotes: 5

Views: 5761

Answers (2)

Guryanov Andrey
Guryanov Andrey

Reputation: 361

Add to file head:

import CoreData

Upvotes: 36

Joshua Nozzi
Joshua Nozzi

Reputation: 61228

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.

Upvotes: 1

Related Questions