3lvis / DATASource

Core Data's NSFetchedResultsController wrapper for UITableView and UICollectionView
Other
106 stars 27 forks source link

Provide a block free alternative #81

Closed 3lvis closed 8 years ago

3lvis commented 8 years ago

Using blocks for the cell configuration is not the best idea. The initial reason why I went for that alternative was because I didn't liked the other alternative: using a delegate for the cell configuration. Specially since that would mean that you could use a DATASource instance that did nothing since the configuration block wasn't provided by default.

But I was wrong, even though is not the best paradigm, is a common paradigm. For example you can easily instantiate a UITableView that does nothing. You have to actually implement it's data source before it can display data. It's a common paradigm, not the best, but is not rare neither.

To not break all the existing apps that are using DATASource right now, I'm providing this implementation as an alternative instead of a replacement.

So now you can do:

class ViewController: UITableViewController {
    weak var dataStack: DATAStack?

    convenience init(dataStack: DATAStack) {
        self.init(style: .Plain)

        self.dataStack = dataStack
    }
    lazy var dataSource: DATASource = {
        let request: NSFetchRequest = NSFetchRequest(entityName: "User")
        request.sortDescriptors = [
            NSSortDescriptor(key: "name", ascending: true)
        ]

        let dataSource = DATASource(tableView: self.tableView, cellIdentifier: CustomCell.Identifier, fetchRequest: request, mainContext: self.dataStack!.mainContext)
        dataSource.delegate = self

        return dataSource
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        self.tableView.dataSource = self.dataSource
}

extension ViewController: DATASourceDelegate {
    func dataSource(dataSource: DATASource, configureTableViewCell cell: UITableViewCell, withItem item: NSManagedObject, atIndexPath indexPath: NSIndexPath) {
        cell.textLabel.text = item.valueForKey("name") as? String ?? ""
    }
}