Search code examples
iosswiftfilternsarraynspredicate

NSPredicate filter array with first character


I'm trying to filter an array with the first letter of name

I'm using this :

let predicate = NSPredicate(format: "name beginswith[c] %@", sections.objectAtIndex(section) as! String)
    let sectionArray = self.mContacts.filteredArrayUsingPredicate(predicate)

Where section is :

let sections = NSArray(objects: "#","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z")

# must contain all the name begin by a digit.

But I can not filter the name begin by digit with this method.

I'm looking for some advices, thanks you


Solution

  • I solve this with MATCHES[c]

    for sectionLetter in sections {
            if (sectionLetter as! String) == "#" {
                let predicateFormat = NSString(format: "name MATCHES[c] '[0-9].*'")
                let predicate:NSPredicate = NSPredicate(format:predicateFormat as String)
    
                let sectionArray = self.mContacts.filteredArrayUsingPredicate(predicate)
                mSectionArray.addObject(sectionArray)
            } else {
                let predicateFormat = NSString(format: "name MATCHES[c] '(%@).*'", sectionLetter as! String)
                let predicate:NSPredicate = NSPredicate(format:predicateFormat as String)
    
                let sectionArray = self.mContacts.filteredArrayUsingPredicate(predicate)
                mSectionArray.addObject(sectionArray)
            }
        }