0

Let's suppose I have an NSArray of Person objects, those are composed of 2 properties( name and age ). Just for the sake of understanding how it works and practice I would like to know how to create a predicate that accesses every member of the array and filters all the objects with an age property that its bigger or equal to 30. I just can't figure that out:

  NSPredicate *predicate = [NSPredicate predicateWithFormat:@">= 30"];

    [persons filteredArrayUsingPredicate:predicate];
    NSLog(@"%@",persons)

What should I type on predicateWithFormat? Thank you in advance!

  • Possible duplicate of [NSPredicate: filtering objects by day of NSDate property](https://stackoverflow.com/questions/1965331/nspredicate-filtering-objects-by-day-of-nsdate-property) – Cristik Oct 26 '18 at 05:36

1 Answers1

0

Two issues:

  1. The predicate format is key - operator - value for example

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age >= 30"];
    

    or with placeholders

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K >= %ld", @"age", 30];
    
  2. filteredArrayUsingPredicate returns a new array

    NSArray *filteredArray = [persons filteredArrayUsingPredicate:predicate];
    NSLog(@"%@", filteredArray)
    

For further information read Predicate Format String Syntax

vadian
  • 274,689
  • 30
  • 353
  • 361
  • Thank you very much for the solution and suggestions! My problem now is that I don't know actually what to put on predicateWithFormat: to specify that the property"age"its inside an object in the Array. Do you have any suggestions? – Stefano Macri Oct 25 '18 at 17:18
  • NVM looks like it does it automatically for me and searches for the member with the property "age"but how the hell does that work out under the hood? – Stefano Macri Oct 25 '18 at 17:36
  • What type is `persons`? The code is supposed to work if `persons` (better `people`) is a dictionary or a custom class. – vadian Oct 26 '18 at 09:23