swift - 使用 Swift 的通用 UITableViewDataSource

标签 swift uitableview generics

我正在尝试创建一个通用的 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/

相关文章:

ios - Swift - 源文件中的编辑器占位符

ios - 创建没有 UI 的 iOS Action 扩展

ios - UITableView 滚动在顶部问题 iOS

swift - 不正确的 UITableViewCell 高度 UIImageView

java - 新的 ArrayList<int>() 在 Java 中失败

generics - 当泛型类型受到泛型生存期的限制时,这意味着什么?

string - 在 Swift 单元测试中比较字符串

ios - 如何配置图像或 ImageView ,以便无论 ImageView 的大小如何,图像都保持其纵横比?

ios - UIScrollView/UITableView 分层效果如Path

Java 泛型不能对泛型 T 使用通配符