This is an example of my model object
class Person: NSObject, NSCoding {
let id: Int
let name: String
let age: Int
init(id: Int, name: String, age: Int) {
self.id = id
self.name = name
self.age = age
}
required init(coder decoder: NSCoder) {
self.id = decoder.decodeInteger(forKey: "id")
self.name = decoder.decodeObject(forKey: "name") as? String ?? ""
self.age = decoder.decodeInteger(forKey: "age")
}
func encode(with coder: NSCoder) {
coder.encode(id, forKey: "id")
coder.encode(name, forKey: "name")
coder.encode(age, forKey: "age")
}
}
I am creating some person objects and adding to an array
let newPerson1 = Person(id:"101", name: "Joe1", age: 10)
let newPerson2 = Person(id:"102", name: "Joe2", age: 11)
var people = [Person]()
people.append(newPerson1)
people.append(newPerson2)
//saving to file
let documentsDirectory = try! FileManager().url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let listOfTasksURL = documentsDirectory.appendingPathComponent("listOfTasks.plist")
NSKeyedArchiver.archiveRootObject(people, toFile: listOfTasksURL.path)
// retrieving from the file
var peopleArray = [Person]()
if let tempArr: [Person] = NSKeyedUnarchiver.unarchiveObject(withFile: listOfTasksURL.path) as? [Person] {
peopleArray = tempArr
}
print(peopleArray)
let data = peopleArray[0]
print(data.id)
I am getting the values succesfully.
I want to search for the 'Person' object with id '101' and delete it from the array and save the modified array back to file.
I want to return a flag if the item is not in the list and add the item to list if its not there.
How can i accomplish this.
Thank you for any help.