arled
arled

Reputation: 2690

Delete the row from data source

Hi I am currently developing a table view based iPhone application using the core data framework. It's going well so far but I struggling with a very simple issue. I've just pick up Swift and am trying to teach myself as well as develop something that can be useful. I have managed to successfully populate a table view with data from the core data database. But, I am struggling with deleting the row from the data source and the tabe view.

Here's the code I'm currently trying:

override func tableView(tableView: UITableView?, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath?) {
        let appDel:AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
        let context:NSManagedObjectContext = appDel.managedObjectContext
        if editingStyle == .Delete {
            println("Delete")
            // Delete the row from the data source
            context.deleteObject(myData.objectAtIndex(indexPath.row) as NSManagedObject)
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }

ScreenShot of the errors: enter image description here

Any suggestions?

Upvotes: 0

Views: 1511

Answers (1)

nhgrif
nhgrif

Reputation: 62062

Optional variables must be unwrapped before you can access their members.

There are two ways to unwrap optional variables.

You can force the unwrap with the exclamation mark:

indexPath!.row

This will however result in a runtime exception if indexPath (whatever variable is being unwrapped) is nil.

Or you can test for nil and unwrap if it's not nil as such:

if let unwrappedIndexPath = indexPath {
    // do something with unwrappedIndexPath.row
}

if let tv = tableView {
    tv.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}

Upvotes: 1

Related Questions