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?
Monitor changes to an array object
Asked Answered
Why not implement your own protocol observable and make the arrays in question conform to that? –
Cenis
Alternatively make a wrapper object that, when updating the Array, calls a didChangeArray() or flips a public bool that you can check. –
Rundown
It's time for bed here. I'll provide it tomorrow (unless someone else comes up wit a smart idea) –
Cenis
If your array is a property in your class, you can use property observers. willSet is called before the change, didSet is called after. It is really easy.
var myArray:[Int] = [1, 3, 4] {
didSet {
println("arrayChanged")
}
}
This will print array changed if I add an Int, remove and Int, etc. I generally put it on one line though:
var myArray:[Int] = [1, 3, 4] { didSet { println("arrayChanged") } }
Thank you, it was very helpful –
Lidstone
Is there any way to monitor internal array changes? Like myArray.append(x)? –
Estis
@PavelAlexeev If you define the
set
for your array it will call for all removeAll
, append
etc changes. –
Robbyrobbyn © 2022 - 2024 — McMap. All rights reserved.