mercredi 23 décembre 2015

Swift: NSClassFromString and NSStringFromClass behave different for NSManagedObjects

NSStringFromClass delivers fully qualified class names for class references like <ClassName>".self"

NSStringClassFromString delivers a class reference of kind AnyClass for fully qualified class names like <AppId>"."<ClassName">.

But it behaves different for subclasses of NSManagedObject.

Let's say the AppId is "MyApp".

class Foo: NSObject {}

@objc(Bar)
class Bar: NSManagedObject {}

print(NSStringFromClass(Foo.self))        // MyApp.Foo
print(NSStringFromClass(Bar.self))        // Bar

print(NSClassFromString("Foo"))           // nil
print(NSClassFromString("Bar"))           // MyApp.Bar
print(NSClassFromString("MyApp.Foo"))     // MyApp.Foo
print(NSClassFromString("MyApp.Bar"))     // nil

That can lead to problems, when creating the input for NSClassFromString dynamically, e.g. by concatenating the 'AppId' with the class name determined by MyClass.self. It seems that subclasses of NSManagedObject don't belong to the Apps namespace.

It's interesting. The functions are reversive.

let fco = NSClassFromString(NSStringFromClass(Foo.self))
let fct = NSClassFromString(NSStringFromClass(fco!))
// fco == fct    

let bco = NSClassFromString(NSStringFromClass(Bar.self))
let bct = NSClassFromString(NSStringFromClass(bco!))
// bco == bct

But the intermediate results differ, as you can see in the upper listing.

Serious question: Is this a bug or a feature? If it's a feature, what are the reasons and advantages.





Aucun commentaire:

Enregistrer un commentaire