我正在尝试创建一个通用的 UITableViewDataSource 实现。在内部,DataSource 实现使用 NSFetchedResultsController 来接收数据。这是我当前的代码。
extension UITableViewCell {
class var reuseIdentifier: String {
return toString(self).componentsSeparatedByString(".").last!
}
}
class ManagedDataSource<CellType: UITableViewCell, ItemType>: NSObject, NSFetchedResultsControllerDelegate, UITableViewDataSource {
// MARK: Properties
var fetchRequest: NSFetchRequest {
get {
return fetchedResultsController.fetchRequest
}
set {
fetchedResultsController = NSFetchedResultsController(fetchRequest: newValue, managedObjectContext: HMServicesManager.mainContext(), sectionNameKeyPath: nil, cacheName: nil)
}
}
private var fetchedResultsController: NSFetchedResultsController {
didSet {
fetchedResultsController.delegate = self
}
}
private let configureCell: (item: ItemType, cell: CellType) -> ()
private weak var tableView: UITableView?
// MARK: Initialization
init(fetchRequest: NSFetchRequest,
tableView: UITableView,
tableViewCellType cellType: CellType.Type,
itemType: ItemType.Type,
configureCell: (item: ItemType, cell: CellType) -> ()) {
self.tableView = tableView
self.configureCell = configureCell
fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: HMServicesManager.mainContext(), sectionNameKeyPath: nil, cacheName: nil)
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(CellType.reuseIdentifier, forIndexPath: indexPath) as! CellType
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 0
}
}
UITableViewDataSource 实现和 NSFetchedResultsControllerDelegate 实现目前不完整,但这不是我的问题。我在 ManagedDataSource 的类定义上遇到编译器错误:
Type 'ManagedDataSource' does not conform to protocol 'UITableViewDataSource'
我不明白为什么编译器会给我一个错误,因为 UITableViewDataSource
所需的方法是由我的类实现的。问题似乎出在泛型上。一旦我删除泛型并改用 AnyObject
,错误就会消失并且我的代码可以正常编译。这不是我想要的,因为那样的话类就不是类型安全的。
最佳答案
现在可以通过 Swift 2.0 实现,无需任何变通方法。
关于swift - 使用 Swift 的通用 UITableViewDataSource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31110748/