Skip to content

Implementing UITableViewDataSource methods in TableViewDataSource #23

Open

Description

@oflannabhra

I wanted to implement swipe-to-delete in one of my UITableViewControllers. This VC displays a table of objects that inherit from ManagedObject and implement ManagedObjectType. To do so, the VC's dataSource needs to implement the tableView(tableView: commitEditingStyle: forRowAtIndexPath:) method, and handle the .Delete case. To delete I simply do the following:

In TableViewDataSource.swift

// MARK: UITableViewDataSource methods
    func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {

        switch editingStyle {
        case .Delete:
            let deleted = dataProvider.objectAtIndexPath(indexPath) as! ManagedObject
            print("Deleted: \(deleted)")
            deleted.delete()

        default: break
        }
    }

delete() is simply:

In ManagedObject.swift

/// ManagedObject - protocol extension that implements defaults
extension ManagedObject {
    public func delete() {
        managedObjectContext?.performChanges({ 
            self.managedObjectContext?.deleteObject(self)
        })
    }
}

Because the TableViewDataSource does not have access to the NSManagedObjectContext, but the ManagedObject does, I am required to cast down to ManagedObject, as the TableViewDataSource's where clause does not actually require ManagedObject.

Is there a better way to handle this? Obviously, I would implement a guard in the cast, but I was wondering if there were a better way to implement deleting an object in this way? Without access to the moc, and without access to the tableView's delegate it seems I have to require some type constraints on the Object to be able to delete.

for reference, the TableViewDataSource generic requirements

class TableViewDataSource<Delegate: DataSourceDelegate, Data: DataProvider, Cell: UITableViewCell where Delegate.Object == Data.Object, Cell: ConfigurableCell, Cell.DataSource == Data.Object>: NSObject, UITableViewDataSource

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions