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!

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

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

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.