Want Swift to monitor the number of Array elements

Asked 2 years ago, Updated 2 years ago, 36 views

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

2022-09-30 19:09

1 Answers

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,

  • Objective-C class must be monitored
  • Monitored properties must be KVC compliant with Objective-C

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.


2022-09-30 19:09

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.