0
votes

I want to let the user of my App delete items from the NSUserDefaults out of a tableView by swiping left on the Cell and press "delete". I know both function but I don't know how to bring them together in the right was so that the "remove swipe" affects the variable in NSUserDefaults. Maybe someone can help me out. Thank you.

This function should allow the User to access the delete Button in a tableView:

func tableView(tableView: UITableView!, canEditRowAtIndexPath indexPath: NSIndexPath!) -> Bool {
    return true
}

func tableView(tableView: UITableView!, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath!) {
    if (editingStyle == UITableViewCellEditingStyle.Delete) 
}

and the function should remove items from NSUserDefaults:

@IBAction func deleteItem(sender: AnyObject) {

    var userDefaults:NSUserDefaults = NSUserDefaults.standardUserDefaults()

    var itemListArray:NSMutableArray = userDefaults.objectForKey("itemList") as NSMutableArray

    var mutableItemList:NSMutableArray = NSMutableArray()

    for dict:AnyObject in itemListArray{
        mutableItemList.addObject(dict as NSDictionary)
    }

    mutableItemList.removeObject(toDoData)

    userDefaults.removeObjectForKey("itemList")
    userDefaults.setObject(mutableItemList, forKey: "itemList")
    userDefaults.synchronize()

}
1

1 Answers

0
votes

First, let's change mutableItemList to an instance variable, which we'll use as the table's data source. Or, you can create a new instance variable and set it accordingly.

var mutableItemList: NSMutableArray!

Then, to delete we call the deleteItem function.

override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if editingStyle == .Delete {
        // Delete the row from the data source
        self.deleteItem(mutableItemList[indexPath.row])
        // show fancy fade animation to remove the cell from the table view
        tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
    }
} 

You can also simplify the deleteItem function. You don't need to rebuild the array and remove the object from NSUserDefaults. You can just delete the object and then set the updated array, which overwrites whatever was there.

func deleteItem(sender: AnyObject) {        
    mutableItemList.removeObject(sender)

    var userDefaults:NSUserDefaults = NSUserDefaults.standardUserDefaults()        
    userDefaults.setObject(mutableItemList, forKey: "itemList")
    userDefaults.synchronize()
}