如何根据值

时间:2017-06-23 11:49:06

标签: ios arrays swift

这是我的模型对象的一个​​例子

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")
    }
}

我正在创建一些人物对象并添加到数组

    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)

我成功地获得了价值观。 我想搜索id为'Person'的{​​{1}}对象,并将其从数组中删除,并将修改后的数组保存回文件。 如果项目不在列表中,我想返回一个标志,如果不在那里,则将项目添加到列表中。 我怎样才能做到这一点。

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

您可以使用index(where:)获取该对象的索引,获取索引后可以轻松地从该数组中删除该对象。

func deleteObject(with id: Int) -> Bool
    if let index = people.index(where: { $0.id == id }) {
        people.remove(at: index)
        return true
    }
    return false
}

//Now use this method like this
if deleteObject(with: 101)  {
    //object is successfully deleted now save data in array
    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)
}
else {
    //object is not present in array add new object
}

答案 1 :(得分:1)

试试这个:

new

更多: Trailing Closure