aryaxt aryaxt - 1 year ago 186
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


Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download