【问题标题】:Generic UITableViewDataSource using Swift使用 Swift 的通用 UITableViewDataSource
【发布时间】: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 uitableview generics


【解决方案1】:

这现在可以通过 Swift 2.0 实现,无需任何解决方法。

【讨论】:

  • 您是否尝试过让ManagedDataSource 在扩展中与UITableViewDataSource 一致?
  • 正如我在回答中所说,现在使用 Swift 2.0 可以实现这一点,无需任何解决方法。使用 Swift 2.0,您只需遵循 UITableViewDataSource。我不知道我在更新到 Swift 2.0 之前是否尝试过遵守使用和扩展的协议,但我想我做到了。
猜你喜欢
  • 2016-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多