优雅的 NSStringFromClass 替代方案

使用 Swift 过程中,我意识到的第一个问题就是没有Objective-C中 NSStringFromClass 的替代方案。在自定义 TableViewCell 时,我喜欢用类名作为 cell 的 identifier,然后在重用队列中,通过 NSStringFromClass 来获得 identifier,从而避免拼写错误。

然而,在 Swift 中,我不得不写一个丑陋的 extension 来达到这一目的。(参考 StackOverflow 的回答)

public extension NSObject{
     public class var nameOfClass: String{
          return NSStringFromClass(self).componentsSeparatedByString(".").last!
     }

     public var nameOfClass: String{
          return NSStringFromClass(self.dynamicType).componentsSeparatedByString(".").last!
     }
}

现在可以使用以下方式实现了

String(MyTableViewCell)

// ListTableViewController
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    // 从重用队列中取出 cell!!!
    let cell = tableView.dequeueReusableCellWithIdentifier(String(ListTableViewCell), forIndexPath: indexPath)

    return cell
}

这样超级赞赞赞的,重复事情说三遍,yeah,yeah,yeah。。。现在可以删掉丑陋的 extension 了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容