Search code examples
cocoacocoa-bindingsnsarraycontroller

Enable NSArrayController predicate based on checkbox


I've got a static filter to turn on/off for an NSArrayController based on whether or not a checkbox is checked. Right now I've bound the checkbox value to this:

private dynamic var filterPending: NSNumber! {
    willSet {
        willChangeValueForKey("filterPredicate")
    }
    didSet {
        didChangeValueForKey("filterPredicate")
    }
}

and then I bound the filter of the NSArrayController to this:

private dynamic var filterPredicate: NSPredicate? {
    guard let filter = filterPending?.boolValue where filter == true else { return nil }
    return NSPredicate(format: "pending > 0")
}

That seems to work properly, but feels like maybe I'm missing some easier way of doing this?


Solution

  • In your set-up the value of filterPredicate depends on the value of filterPending. As Gerd K points out, the Key-Value Observing API allows you to specify this type of relationship by registering filterPending as a dependent key of filterPredicate:

    // MyFile.swift
    
    class func keyPathsForValuesAffectingFilterPredicate() -> Set<NSObject> {
        return Set<NSObject>(arrayLiteral: "filterPending")
    }
    
    private dynamic var filterPending: NSNumber!
    
    private dynamic var filterPredicate: NSPredicate? {
        guard let filter = filterPending?.boolValue where filter == true else { return nil }
        return NSPredicate(format: "pending > 0")
    }