ios - NSClassFromString 不工作

标签 ios swift core-data

这是我遇到的这个代码案例的问题:

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 是 CoreData 实体的名称, arrayOne, ..... arrayFour 是某种数组(对于问题来说不是那么重要)。

我需要使用什么确切的代码来获取循环内每个实体的类型?

最佳答案

您的第二个 for 循环没有意义。你能试试吗?

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

编辑 1

目前我正在做一个使用 NSClassFromString 的项目。这就是我在代码中使用它的方式。

在我的主课中我使用:

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

用户选择 selectedBrand 和 selectedModel 的位置。

在汽车类中,我有一个初始化函数

override init() {
    super.init()

    // My codes here like initializing webview

}

希望对你有帮助

关于ios - NSClassFromString 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44948447/

相关文章:

iphone - 远程更新 iOS 资源文件

ios - 从一个实体到多个实体的核心数据关系

cocoa-touch - NSFetchedResultsController 委托(delegate)异常

iphone - UITableViewCell 文本的字体和颜色是什么?

IOS 本地化声音文件无法在设备上运行

ios - Xcode 8 表格 View 单元格到不同的 View

iOS swift : Find index for CKRecord in array

swift - 如何保存/存储从 Parse 发送的推送通知并将其打印在任何 View Controller 上?

ios - UIWebView for GIF 后台loadData方法报错

ios - 在多个上下文中保持 NSManagedObjects 同步