Elina
Elina

Reputation: 79

Delete an object from an array

I have created two buttons (add and edit):

var addButton = UIBarButtonItem(title: "Add", style: .Plain, target: self, action: "tabBarAddClicked"); self.navigationItem.rightBarButtonItems = [self.editButtonItem(), addButton]

These also work and I can delete objects from the tableView with the function

override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
   if editingStyle == UITableViewCellEditingStyle.Delete {
        subjects.removeAtIndex(indexPath.row)
        tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
    }
}

Hereby:

var subjects: [Subject] = subjectsData

and

var subjectsData = [ Subject(name: "Investments", semester: 1), Subject(name: "Statistics", semester: 1), Subject(name: "Studium Universale", semester: 2) ] 

Though, when I go back in the navigation bar to the previous screen and then return to the screen, the deleted objects from the array are again there. But I told it to remove the objects from the array subjectsData with subjects.removeAtIndex(indexPath.row).

Why do the objects return and how can I change that?

Upvotes: 0

Views: 55

Answers (1)

MirekE
MirekE

Reputation: 11555

But I told it to remove the objects from the array subjectsData with subjects.removeAtIndex(indexPath.row).

You told it to remove from subjects, not subjectsData.

For example:

var array1 = [1, 2, 3]
var array2 = array1


array2.removeFirst()

print(array1) // [1, 2, 3]
print(array2) // [2, 3]

Upvotes: 1

Related Questions