使用 Swift 過程中,我意識到的第一個問題就是沒有Objective-C中 NSStringFromClass 的替代方案。在自定義 TableViewCell 時,我喜歡用類名作為 cell 的 identifier绰疤,然后在重用隊(duì)列中,通過 NSStringFromClass 來獲得 identifier舞终,從而避免拼寫錯誤轻庆。
然而,在 Swift 中敛劝,我不得不寫一個丑陋的 extension 來達(dá)到這一目的余爆。(參考 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)在可以使用以下方式實(shí)現(xiàn)了
String(MyTableViewCell)
// ListTableViewController
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// 從重用隊(duì)列中取出 cell!!!
let cell = tableView.dequeueReusableCellWithIdentifier(String(ListTableViewCell), forIndexPath: indexPath)
return cell
}
這樣超級贊贊贊的,重復(fù)事情說三遍夸盟,yeah蛾方,yeah,yeah。桩砰⊥卮海。現(xiàn)在可以刪掉丑陋的 extension 了亚隅。