0

I am using Xcode 8, Swift 3 and Core Data. In all my NSManagedObject classes I include entityName property. How do I make sure that all classes derived from NSManagedObject have the entityName property, like below:

public class MUAccount: NSManagedObject {
    static let entityName: String = "MUAccount"
}

I tried creating a protocol, and making NSManagedObject confirm to that; however, that didn't work out:

protocol EntityNameAvailable {
    static var entityName: String { get }
}

extension NSManagedObject: EntityNameAvailable {
    internal static var entityName: String {
        return "undefined"
    }
}

The above code doesn't work. Is what I am asking possible with Swift? If not, is it possible with any other OOP language, C++, Java?

oyalhi
  • 3,834
  • 4
  • 40
  • 45
  • 1
    A "static" property is "final" and cannot be overridden in a subclass. See http://stackoverflow.com/a/31113986/1187415 for some possible solutions. – Martin R Jan 13 '17 at 13:57
  • The link provided is actually exactly what I was looking for!. Instead of func I made it a variable though. And instead of `split`, I used `classString.components(separatedBy: ".")`. Thank you! – oyalhi Jan 13 '17 at 14:18
  • Yes, that is old Swift code. In Swift 3 you can simplify it so `return String(describing: self)`. – But note that if you create the NSManagedObject subclasses with Xcode 8 then you should already have an auto-generated property for the entity name. – Martin R Jan 13 '17 at 14:50
  • I choose Manual/None for Codegen, but I do create the NSManagedObject subclasses with Xcode 8. I only get auto generated fetchRequest like so: `@nonobjc public class func fetchRequest() -> NSFetchRequest { return NSFetchRequest(entityName: "MUAccount"); }`. No property name for the entity name. – oyalhi Jan 13 '17 at 14:59
  • You are right, I mixed things up. What I meant is that in iOS 10/macOS 10.12, NSManagedObject already has a `class func entity()` . – Martin R Jan 13 '17 at 15:16
  • Yes you are right. I can now use: `MUAccount.entity().managedObjectClassName`. Thanks again. – oyalhi Jan 13 '17 at 15:29

0 Answers0