美文网首页
优雅的 NSStringFromClass 替代方案

优雅的 NSStringFromClass 替代方案

作者: 城市之光 | 来源:发表于2016-01-29 10:17 被阅读92次

使用 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 了。

相关文章

网友评论

      本文标题:优雅的 NSStringFromClass 替代方案

      本文链接:https://www.haomeiwen.com/subject/bdyjkttx.html