简体   繁体   中英

Filtering array of custom objects with NSPredicate via binding

class MyClass {
    var result: Bool

    init(result: Bool) {
        self.result = result
     } 
}

I have an array( [MyClass] ) in my ArrayController connected via binding and I need to filter this array by property result .

For example half of these objects have result as false, I only want to display these items which have result == true , but it must be done with NSPredicate and I don't have any clue how to make this predicate, any ideas?

To make it clear, I'm required to use filterPredicate variable of NSArrayController to filter this array.

First of all, your class MyClassmust conform to NSObject, this turns the declaration into,

class MyClass: NSObject {
var result: Bool
init(result: Bool) {
    self.result = result
 } 
}

then you can apply the NSPredicate as,

let bPredicate: NSPredicate = NSPredicate(format: "result contains[cd]       %@", true)
let searchArray = yourArray.filtered(using: bPredicate) as NSArray

Ok, I solved problem by myself. Here is the code

arrayController.filterPredicate = NSPredicate { object, _ in
    (object as? MyClass)?.result
}

for dynamic var

dynamic var predicate: NSPredicate? = {
    return NSPredicate { object, _ in
        (object as? MyClass)?.result
    }
}()

用户筛选器代替NSPredicate

'let filteredArray = yourArray.filter({$0.result == true})'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM