0

I have a collection of contacts I would like to filter: var arraycontacts: NSMutableArray = []

arraycontacts contains a large list of FriendModel Objects:

    var friend = FriendModel(
        name: self.contactName(contact),
        phone: self.contactPhones(contact),
        email: self.contactEmails(contact),
        phoneString: self.contactPhonesString(contact)
    )
    self.arraycontacts.addObject(friend)

I'd like to be able to use filterContentSearchText, to limit this array to users that match or are LIKE a name string. Basically, I'd like to search by name.

This is my attempt:

func filterContentForSearchText(searchText: String, scope: String = "All") {
    let namePredicate = NSPredicate(format: "name like %@", searchText)
    let term = self.arraycontacts.filteredArrayUsingPredicate(namePredicate!)
    println(term)
}

My above code produces the following error: this class is not key value coding-compliant for the key name.

Obviously, the predicate can't see the name property on my FriendModel object. How can I fix my query?

Thanks!

JZ.
  • 21,147
  • 32
  • 115
  • 192

1 Answers1

4

First, drop the NSMutableArray and just use var arrayContacts: [FriendModel] = [].

Then use the filter method on the array.

var friend = FriendModel(
        name: self.contactName(contact),
        phone: self.contactPhones(contact),
        email: self.contactEmails(contact),
        phoneString: self.contactPhonesString(contact)
    )
self.arraycontacts.append(friend)

let filteredArray = self.arrayContacts.filter() {
   $0.name.hasPrefix(searchString)
}

Or something like that anyway.

Here you go...

enter image description here

Fogmeister
  • 76,236
  • 42
  • 207
  • 306
  • 1
    Thank you! Perfect idea. The key to my problem was setting the array var array: [AnyObject] = self. arraycontacts in order to use the swift Array filter() – JZ. Feb 26 '15 at 17:41