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