0
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.

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

As I mention earlier I'm required to use filterPredicate of an NSArrayController, not creating new array.
1

User Filter instead of NSPredicate

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

Comments

0

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
    }
}()

3 Comments

How is this using the binding?
Ahh, right, just forgot to paste code for dynamic var.
What did you bind to what? If you bind the filter predicate of the array controller, you don't have to set it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.