NSPredicate – How to filter an array

To filter an array NSPredicate objects comes in hand. For example, you have an array of Person objects, with members like name, address, phone number etc. Now you want to filter the array using search bar as input. Using NSPredicate this array may be filtered as follows:

Attribute name is the key path of the member you want to filter the array by. So we want to filter this array by the member name. The value we are filtering by is the input in the search bar. NSPredicate object is created with format %K (key path, name in this case), we want to have all objects with member name containing attribute value. String comparisons are by default case and diacritic sensitive so ‘[cd]’ is appended to the ‘contains’ word; it makes the string comparisons case and diacritic insensitive.

For other filtering options, check out Apple’s Predicate Programming Guide – Predicate Format String Syntax.

Related Post

Remember to share...Share on FacebookTweet about this on TwitterShare on Google+Share on LinkedInEmail this to someone

Leave a Reply

Your email address will not be published. Required fields are marked *