4

I'm attempting to filter an array of arrays which contains a core data entity of type Bird. The entities have been split into arrays of arrays based on a UITableView with sections and rows.

To search I have the following method based on this question NSPredicate on array of arrays:

func filterContentForSearchText(searchText: String) {
    let resultPredicate = NSPredicate(format: "SELF[0].common_name contains[cd] %@", searchText)
    self.filteredBirds = self.birds.filteredArrayUsingPredicate(resultPredicate!)
}

This however results in the error

Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex:]: index 0 beyond bounds for empty array'

which probably makes sense because the array has 27 (A-Z, #) elements of which some have no entities

So, how can I adjust the NSPredicate query to take into consideration some arrays maybe empty?

2
  • Why do you have the empty arrays? Are they useful? Get rid of them. The other answer you refer to is a different problem, you don't want to index into the array, you want to check the full array contents... Commented Mar 14, 2015 at 12:37
  • There are empty arrays because UILocalizedIndexedCollation generates the array of indexes (A-Z, #) based on the users locale Commented Mar 14, 2015 at 21:31

2 Answers 2

5
 let resultPredicate = NSPredicate(format: "SELF.@count >0  AND SELF[0].common_name contains[cd] %@", searchText)
Sign up to request clarification or add additional context in comments.

3 Comments

Please provide context with your answer.
Thanks for the answer - Adding the count did get around the empty array issue but @AirspeedVelocity answer did solve the root of the problem to filter an array of arrays.
@count did help me!
0

If you’re interested in a stronger-typed filtering operation, and you’re using the latest Xcode 6.3, you can use flatMap, which will perform a mapping operation that returns arrays on an array of arrays, and flattens the result. Then you can use filter in the subarrays:

// assuming birds is an NSArray containing NSArrays of Bird
if let arrayOfArrays = birds as? [[Bird]] {
    let filteredBirds = arrayOfArrays.flatMap { birds in
        birds.filter { bird in
            bird.common_name.rangeOfString(searchText) != nil
        }
    }
}

Comments

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.