aryaxt
aryaxt

Reputation: 77596

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);

Upvotes: 3

Views: 2163

Answers (4)

aryaxt
aryaxt

Reputation: 77596

Switf 2 solutions

let className = String(Int.self) // String

let className2 = String(4.dynamicType) // Int

func doThings<T>(type: T.Type) -> String {
    return String(T) // Whatever type passed
}

Upvotes: 1

dr OX
dr OX

Reputation: 4739

quickly in Swift:

let className = String(YourClass)

Extension variant (in my opinion, it's more convenient):

extension NSObject {
    class var string: String{
        get {
            return String(self)
        }
    }
}

//using:
let className = YourClass.string

Upvotes: 2

Ivica M.
Ivica M.

Reputation: 4823

Swift classes can be given a custom Objective-C name, what will make NSStringFromClass print a nicer output in a playground.

import CoreData

@objc(User) class User : NSManagedObject {

}

let className = NSStringFromClass(User.self) // className will be "User" 

Without it, NSStringFromClass will print 'ModulName.ClassName' which is arguably better than 'ClassName' only. The ugliness of the playground output is due to the fact that playgrounds have some cryptic implicit module names.

Upvotes: 5

Mundi
Mundi

Reputation: 80265

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.

Upvotes: 4

Related Questions