NSPredicate to get items of some length in a NSSet

Hi,

A new question for today.

I have a NSSet with 150 000 strings, whose length varies from 2 to 20.

I want to get a NSSet with only the strings whose length is between 6 and 10.

filteredSetWithPredicate seems to be useful for that ; the syntax should then be :

set myPredicate to current application's NSPredicate's ???????
myNSSet's filteredWithPredicate:myPredicate

How can I define myPredicate to obtain the adequate filter ?

Thanks,
Nicolas

Try something like “self.length > 5 AND self.length < 21”. Or “self.length BETWEEN { 6, 20 }”.

??? =


predicateWithFormat:"length < 11 AND length > 5"

Thanks to both of you, again,

This is what I wrote, but the set after filtering has the same number of items than before.

set setDesKeys to current application's NSSet's setWithArray:{"cdeinoprty","abehiilmorsttty","abceiirt","eepprsst","celov","aa","a","ab"}
        set myPredicate to current application's NSPredicate's predicateWithFormat:"length > 4"
        setDesKeys's filteredSetUsingPredicate:myPredicate

I tried also to define the predicate as below, with the same result :

set myPredicate to current application's NSPredicate's predicateWithFormat:"self.length > 4"

What am I missing ?

Regards,
Nicolas

The code works:

0000.002 [13] set setDesKeys to current application's NSSet's setWithArray:{"cdeinoprty", "abehiilmorsttty", "abceiirt", "eepprsst", "celov", "aa", "a", "ab"}
--> {eepprsst, abehiilmorsttty, aa, cdeinoprty, celov, a, ab, abceiirt}
0000.002 [14] set myPredicate to current application's NSPredicate's predicateWithFormat:"length > 4"
--> length > 4
0000.003 [15] setDesKeys's filteredSetUsingPredicate:myPredicate
--> {cdeinoprty, eepprsst, abehiilmorsttty, abceiirt, celov}

You just need to store the result, something like:

set setDesKeys to setDesKeys's filteredSetUsingPredicate:myPredicate

the filteredSet. method returns a new set containing the filtered objects, the original set is left unchanged


set filteredSet to setDesKeys's filteredSetUsingPredicate:myPredicate

PS: NSMutableSet can be filtered directly


set setDesKeys to current application's NSMutableSet's setWithArray:{"cdeinoprty","abehiilmorsttty","abceiirt","eepprsst","celov","aa","a","ab"}
       set myPredicate to current application's NSPredicate's predicateWithFormat:"length > 4"
       setDesKeys's filterUsingPredicate:myPredicate

Many thanks to both of you, it works perfectly !

Regards,
Nicolas

FYI, I suspect the “BETWEEN” method might be a shade quicker.