【发布时间】:2015-06-29 08:09:52
【问题描述】:
我正在尝试创建一个通用的 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 的类定义上遇到编译器错误:
类型“ManagedDataSource”不符合协议“UITableViewDataSource”
我不明白为什么编译器会给我一个错误,因为UITableViewDataSource 所需的方法是由我的类实现的。问题似乎与泛型有关。一旦我删除泛型并改用AnyObject,错误就会消失,我的代码编译得很好。但这不是我想要的,因为那样类不是类型安全的。
【问题讨论】:
-
这是不可能的,因为通用 Swift 方法对 Objective-C 不可见。有关非常相似的问题,请参阅 stackoverflow.com/questions/26097581/…。
标签: swift uitableview generics