基于复选框启用 NSArrayController 谓词

Enable NSArrayController predicate based on checkbox

我有一个静态过滤器可以根据复选框是否被选中来为 NSArrayController 转换 on/off。现在我已经将复选框值绑定到这个:

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

然后我将 NSArrayController 的过滤器绑定到这个:

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

这似乎工作正常,但感觉我可能缺少一些更简单的方法?

在您的设置中,filterPredicate 的值取决于 filterPending 的值。正如 Gerd K 指出的那样,Key-Value Observing API 允许您通过注册 filterPending 作为 filterPredicatedependent key:

// 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")
}