无法从字符串创建类Swift
我试图从Swift中的字符串中获取类。这不是工作。我尝试以下操作:无法从字符串创建类Swift
打印(NSClassFromString(词典[关键]) - “错误”!)
它产生 “错误”。然而,在日志中,我可以看到
po dictionary[key]!
"VacanciesCell"
为什么会这样呢?
空缺细胞定义为:
import UIKit
class VacanciesCell: BaseCell, ModelBinding {
...
}
问题通过以下解决:
for (key, _) in dictionary {
print(NSClassFromString(dictionary[key]!) ?? "error")
print("key - \(key) val \(dictionary[key]!)")
let cellClassStr = "AppName.\(dictionary[key]!)"
self.register(NSClassFromString(cellClassStr), forCellReuseIdentifier: key)
}
其中 “AppName的” 是应用程序的名称。
我想你的意思是“模块名称”,而不是“应用程序名称”。 – Sulthan
这听起来像是一种可怕的方式来注册你的课程。无论如何,你如何将类名存储到字典中?你为什么不直接存储类并调用接收类的'register ...'方法? – EmilioPelaez
@Sulthan我不知道区别,我添加应用程序名称作为字符串。 –
你为什么想这样做? - 你看过https://*.com/questions/24030814/swift-language-nsclassfromstring中的各种答案吗? –
@MartinR因为我想获得单元类来注册它。 –
@Hamish我编辑了我的文章,有没有其他需要的信息? –