5

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)")
    }
user2414590
  • 123
  • 1
  • 7

2 Answers2

36

Add to file head:

import CoreData
Guryanov Andrey
  • 361
  • 3
  • 3
1

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.

Joshua Nozzi
  • 60,946
  • 14
  • 140
  • 135
  • Why i should have one?The purpose of Entity is exactly to avoid this?If i don't have how i should proceed, instead [Company] to write [NSManagedObject] ? – user2414590 Jan 11 '16 at 21:05
  • I think you misunderstand some basics. Consider how the type-safe Swift language could possibly accept a string as a distinct type and know anything about that type. If you don't want that benefit, yes, you'd just have an array of NSManagedObject. – Joshua Nozzi Jan 12 '16 at 00:17
  • What are the benefits of creating separate class for every Entity? – user2414590 Jan 12 '16 at 14:23
  • 1
    Please read the documentation: https://developer.apple.com/library/tvos/documentation/Cocoa/Conceptual/CoreData/LifeofaManagedObject.html#//apple_ref/doc/uid/TP40001075-CH16-SW1 If your model objects (entity instances) have custom logic, this is needed; otherwise, the only benefit is ease of use with the strongly-typed Swift language (ie, you can cast as an array of class `Company: NSManagedObject` and access properties without string keys. But that alone is a **huge** benefit as it helps avoid many common programming errors that only appear at runtime (ie, they'll compile but won't run right) – Joshua Nozzi Jan 12 '16 at 14:48