[英]How to perform a class method of a class which is casted from NSClassFromString?
I tried to use a class which is created from NSClassFromString to perform a class method, but I failed. 我尝试使用从NSClassFromString创建的类执行类方法,但失败了。
In Objective-C, it's easy: 在Objective-C中,这很容易:
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:[NSClassFromString(reuseIdentifier) cellStyle] reuseIdentifier:reuseIdentifier];
if (self) {
let sel = #selector(CTFeedbackTopicCellItem.cellStyle())
// Initialization code
}
return self;
}
And in Swift it's not easy: 在Swift中,这并不容易:
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
if let reuseIdentifier2 = reuseIdentifier
{
if let class2 = NSClassFromString(reuseIdentifier2) as? NSObjectProtocol
{
let sel = #selector(CTFeedbackCellItem.cellStyle())
if let class3 = class2 as? CTFeedbackCellItem
{
super.init(style: class3.cellStyle, reuseIdentifier: reuseIdentifier2)
}
}
}
}
The error shown in my Swift code so far are: 到目前为止,我的Swift代码中显示的错误是:
1. Argument of '#selector' does not refer to an '@objc' method, property or initializer. 1.“ #selector”的参数未引用“ @objc”方法,属性或初始化程序。
2. Stastic member 'cellType' cannnot be used on instance of type 'CTFeedbackCellItem' 2.无法将静态成员“ cellType”用于类型为“ CTFeedbackCellItem”的实例
Try this: 尝试这个:
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
guard let reuseIdentifier = reuseIdentifier else {
fatalError("bad usage")
}
guard let itemClass = NSClassFromString(reuseIdentifier) as? CTFeedbackCellItem.Type else {
fatalError("bad reuseIdentifier")
}
super.init(style: itemClass.cellStyle(), reuseIdentifier: reuseIdentifier)
}
(If you have implemented your cellStyle
as a class property, change itemClass.cellStyle()
to itemClass.cellStyle
.) (如果将cellStyle
实现为类属性,则将itemClass.cellStyle()
更改为itemClass.cellStyle
。)
Class object is not an instance of the class, so you should not cast it like an instance. 类对象不是类的实例,因此您不应将其像实例一样进行转换。 Cast it to meta-class, if you want to call class methods. 如果要调用类方法,则将其强制转换为元类。 No need to use #selector
. 无需使用#selector
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.