優(yōu)雅的 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!
     }
}

現(xiàn)在可以使用以下方式實現(xiàn)了

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。。。現(xiàn)在可以刪掉丑陋的 extension 了。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容