18

I have no idea if this is possible at all, but it would save me from a lot of stress and bad code. Is it possible to monitor whenever an array gets updated? For example, method A changes the array a=[1,2,3] to a=[1,2,3,4], is it possible to have a sort of delegate that gets triggered when a is updated?

4

1 回答 1

36

如果你的数组是你类中的一个属性,你可以使用属性观察者。willSet 在更改之前调用, didSet 在更改之后调用。这真的很容易。

var myArray:[Int] = [1, 3, 4] {
    didSet {
        println("arrayChanged")
    }
}

如果我添加一个 Int、remove 和 Int 等,这将打印更改的数组。不过,我通常将它放在一行上:

var myArray:[Int] = [1, 3, 4] { didSet { println("arrayChanged") } }
于 2015-02-11T01:34:09.927 回答