Reputation: 77596
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
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
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
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
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