Sjakelien Sjakelien - 1 year ago 143
iOS Question

Filtering EKEvent with NSPredicate

I have an NSArray with EKEvents, that I need to filter down to a clean list.

I'm looking for an NSPredicate that filters out all Events of which the 'title' attribute, which is an NSString, starts with a numeric value.

So, I want to take out those Titles that look like '123Something' and '8somethingElse' but keep 'Anything123' and of course 'specificallyThisOne'.

I rely on your smartness, and, since I really don't have a clue on where to get started, an explanation would also highly appreciated!

Answer Source

NSPredicate supports regular expression which provides the most convenient way to filter strings.

This is an example with a custom array of dictionaries, it's supposed to work also with an array of EKEvent.

The regex filters all strings which

  • start ^
  • with one or more digits \\d+
  • and ignore the rest of the string .*$.

Since you didn't mention the language this is Swift:

let array = [["name" : "alpha", "title" : "123Something"],
             ["name" : "beta", "title" : "8somethingElse"],
             ["name" : "gamma", "title" : "Anything123"],
             ["name" : "delta", "title" : "specificallyThisOne"]]

let regex = "^\\d+.*$"
let predicate = NSPredicate(format:"title MATCHES %@", regex)

let filteredArray = (array as NSArray).filteredArrayUsingPredicate(predicate)

It's even possible without NSPredicate using the native filter function

let filteredArray =  array.filter { $0["title"]!.rangeOfString(regex, options: .RegularExpressionSearch) != nil }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download