2

I have an NSArray of objects with the following properties

@objc class Dummy: NSObject {
    let propertyOne: Int
    let propertyTwo: Int
    let propertyThree: NSDictionary
}

In propertyThree, it will have certain key values pairs such as

keyOne => valueOne
keyTwo => valueTwo
keyThree => valueThree

I want to filter through my NSArray of Dummy Objects based off of keyOne of the NSDictionary that is a property of the Dummy object.

How would I go about doing this? I looked through:

But it doesn't seem applicable.

Community
  • 1
  • 1
Will Hua
  • 1,729
  • 2
  • 23
  • 33
  • How about using the `filter` method on your array? You just need to provide a closure which returns true or false for a certain element. – Kametrixom Aug 22 '15 at 23:29

3 Answers3

5

You don't provide any code about you're using NSPredicate, so I wrote a simple example. Maybe this will help you.

@objc class Dummy: NSObject {
    let propertyOne: Int = 1
    let propertyTwo: Int = 1
    let propertyThree: NSDictionary

    init(dict: NSDictionary) {
        propertyThree = dict
        super.init()
    }
}

let arr: NSArray = [
    Dummy(dict: ["keyOne" : "one"]),
    Dummy(dict: ["keyOne" : "two"]),
    Dummy(dict: ["keyOne" : "three"]),
    Dummy(dict: ["keyOne" : "one"]),
    Dummy(dict: ["keyOne" : "five"])
]

let predicate = NSPredicate(format: "SELF.propertyThree.keyOne == 'one'")
let results = arr.filteredArrayUsingPredicate(predicate)
print(results)
Bannings
  • 10,376
  • 7
  • 44
  • 54
1

In Objective-C:

[array filteredArrayUsingPredicate:[NSPredicate 
                         predicateWithFormat:@"propertyThree.keyOne = %@", value]];

In Swift you could use the adaptation of that but, as Kametrixom suggests, it'd be more normal to use filter and a closure; that's the mechanism that removes the dynamic key-value coding step.

Tommy
  • 99,986
  • 12
  • 185
  • 204
0

Here you go, using real Swift:

class Dummy {
    let propertyOne: Int = 1
    let dict: [String : String]

    init(dict: [String : String]) {
        self.dict = dict
    }
}

let arr = [
    Dummy(dict: ["keyOne" : "one"]),
    Dummy(dict: ["keyOne" : "two"]),
    Dummy(dict: ["keyOne" : "three"]),
    Dummy(dict: ["keyOne" : "one"]),
    Dummy(dict: ["keyOne" : "five"])
]

let result = arr.filter { $0.dict["keyOne"] == "one" }

Few notes:

  • You don't need your classes to inherit from NSObject in Swift, if they do though, the @objc attribute is implicitly applied anyways
  • Use [NSObject : AnyObject] instead of NSDictionary as it's equivalent. I used [String : String] here because that's obviously what it is
  • Using the filter method, you can filter your array in a typesafe way, also it's faster
Kametrixom
  • 14,673
  • 7
  • 45
  • 62