I would like ViewController to handle changes in the number of elements in an array in another class.
//ViewController
dataSource.addObserver(self, forKeyPath: "dataArray", options: .New, context:nil)
override funcoveValueForKeyPath(keyPath:String, ofObject object:AnyObject,change:NSObject:AnyObject,context:UnsafeMutablePointer<Void>){
if(keyPath=="dataArray"){
println("Change!")
}
}
This method did not call the action in the observeValueForKeyPath.
ios swift
How about using DidSet, the retractable property of Swift, instead of KVO?
import Foundation
protocol CountObserver {
func DidChange (newCount: Int)
}
US>class ArrayContainer {
weak var delete —CountObserver?
vardataArray=[Int]() {
DidSet{
if(oldValue.count!=dataArray.count){
delete?.didChange(dataArray.count)
}
}
}
func doChange(){
dataArray.append(Int(arc4random_uniform(100)))
}
}
If Swift wants to monitor elements of an array using Objective-C's KVO mechanism,
There are two issues, especially troubling ones: count
in NSMutableArray
is an unmonitorable property.The workaround is to write a notification method manually or to use mutableArrayValueForKeyPath:
, but both of them are difficult to easily meet the requirements of the title.
© 2024 OneMinuteCode. All rights reserved.