加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

优雅的 NSStringFromClass 替代方案

发布时间:2020-12-14 07:19:36 所属栏目:百科 来源:网络整理
导读:作者:Natasha The Robot,原文链接,原文日期:2016-01-14 译者:saitjr;校对:千叶知风;定稿:Cee 使用 Swift 过程中,我意识到的第一个问题就是没有 NSStringFromClass 的替代方案。在自定义 TableViewCell 时,我喜欢用类名作为 cell 的 identifier,

作者:Natasha The Robot,原文链接,原文日期:2016-01-14
译者:saitjr;校对:千叶知风;定稿:Cee

使用 Swift 过程中,我意识到的第一个问题就是没有 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!
    }
}

不知道以下写法是什么时候出现的,但我确实在 @aligatr 发表的文章中看到了:

// This now works!!!
String(MyTableViewCell)

为确保这个方案可行,我在自己的工程中试了试,没想到真的成功了!!

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

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

        return cell
    }

超级赞赞赞,我终于可以删掉丑陋的 extension 了。

本文由 SwiftGG 翻译组翻译,已经获得作者翻译授权,最新文章请访问 http://swift.gg。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读