Michel
Michel

Reputation: 11755

NSClassFromString not working

Here is an issue I have with this case of code:

let entityTypeDico = ["entityTypeOne": arrayOne, "entityTypeOneTwo": arrayTwo,
                      "entityTypeThree": arrayThree, "entityTypeFour": arrayFour];

for (entityName, arrayItem) in entityTypeDico {
    for x in arrayItem {
      /*do something with x and arrayItem
      I need to use the class of entityName */
      //To get it I tried to use some code like:
      NSClassFromString(entityName) // But it does not work.
    }
}

entityTypeOne, ..... entityTypeFour are names of CoreData entities, arrayOne, ..... arrayFour are some kind of arrays (not so important for the question).

What exact code do I need to use to get hold of the type of each entity inside the loop?

Upvotes: 0

Views: 182

Answers (2)

Michel
Michel

Reputation: 11755

Here what I ended up by finding after a number of experiments. It works and does what I want. I hope it will be useful to some other people too.

let entityTypeDico = ["entityTypeOne": arrayOne, "entityTypeOneTwo": arrayTwo,
                      "entityTypeThree": arrayThree, "entityTypeFour": arrayFour];

// "entityTypeXYZ" is a class name (subclass of NSManagedObject)
// arrayXYZ is some array (not so important for the question)

for (entityName, arrayItem) in entityTypeDico {
    for x in arrayItem {
      /*do something with x and arrayItem
      I need to use the class of entityName */
      //To get it I tried to use some code like:
      NSClassFromString(entityName) // But it did not work.
      // Here is what finally worked for me:
      ((NSClassFromString("\(entityName)")) as! NSManagedObject.Type)
    }
}

Upvotes: 0

Burak Gavas
Burak Gavas

Reputation: 1354

Your second for loop doesnt make sense. Can you try?

for (entityName, arrayItem) in entityTypeDico {
    NSClassFromString("YourProjectName.\(entityName)")
}

Edit 1

Currently I am working on a project where I used NSClassFromString. And that is how I used it in my code.

In my main class I use:

let carClass = NSClassFromString("MyProjectName.\(self.selectedBrand)\(self.selectedModel)") as! NSObject.Type
_ = carClass.init()

where selectedBrand and selectedModel are picked by the user.

In the car class, I have an init function

override init() {
    super.init()

    // My codes here like initializing webview

}

Hope it helps

Upvotes: 2

Related Questions