且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Swift中根据字符串创建对象?

更新时间:2023-11-15 12:40:04

您需要的代码更多.您将获得一个AnyClass而不是AnyObject.因此,您需要创建该类型的实例.您可以尝试以下方法:

You need a little more code than that. You will get an AnyClass and not an AnyObject. So you need to create an instance of that type. You could try this:

let cellClass: AnyClass! = NSClassFromString("MyCell")
var objectType : NSObject.Type! = cellClass as NSObject.Type!
var theObject: NSObject! = objectType() as NSObject
var myCell:MyCell = theObject as MyCell

要使其符合您的协议,您可以尝试以下几种方法:

For letting it conform to your protocol you could try a couple of things:

1.您可以为所有符合协议的单元创建基类.并在上面的代码中使用它而不是UITableViewCell.为此,您可以使用如下代码:

protocol SetCell {
    func setcell() {}
}
class BaseUITableViewCell : UITableViewCell, SetCell {
    func setcell() {}
}
class MyCell : BaseUITableViewCell {
    override func setcell() {}
}

let cellClass: AnyClass! = NSClassFromString("MyCell")
var objectType : NSObject.Type! = cellClass as NSObject.Type!
var theObject: NSObject! = objectType() as NSObject
var myCell:BaseUITableViewCell = theObject as BaseUITableViewCell

2.您可以使用扩展名来扩展UITableViewCell,例如添加一个空扩展名

extension UITableViewCell: SetCell {}

//编译时错误:

Declarations from extensions cannot be overridden yet

//Edwin:奇怪,在文档中.看来这是出门了...

//Edwin: Strange, this is in the documentation. So it looks like this one is out...

3.您可以定义一个符合以下协议的变量:

@objc protocol SetCell {
    func setcell() {}
}

let cellClass: AnyClass! = NSClassFromString("MyCell")
var objectType : NSObject.Type! = cellClass as NSObject.Type!
var myCell2:protocol<SetCell> = objectType() as protocol<SetCell>