aryaxt aryaxt - 4 months ago 7
Swift Question

Swift - Get class name from MetaType?

In the example below T refers to a type that extends NSManagedObject, so why can I not call.

I do not have access to an instance of the class

private func getNewManagedObject <T: NSManagedObject>(type: T.Type) -> T {

// Let's assume all Entity Names are the same as Class names
let className = "" /*Somehow get class name from type ("User")*/
return NSEntityDescription.insertNewObjectForEntityForName(className, inManagedObjectContext: managedObjectContext) as T
}

getNewManagedObject(User.self);

Answer

With some experimenting I found out the following. In Playground you can do

class User : NSManagedObject {
}

let s = NSStringFromClass(User)  // cryptic output: "__lldb_expr_XX.User"

The XX is some random number. At this point you can get the entity name with

let entityName = s.pathExtension // "User"

It's a bit hacky but maybe it could work for you.

Comments