-1

Hey i want to filter an NSArray. In this Array is a lot of information like name, town, telephonenumber, and so on. But some towns are twice or three times in the array.
I have property with a town in it.
So i want only those objects from the arry which match with the property.

For example: in the Array stands:

  1. Frank, New York, 123456
  2. Oliver, New York, 123456
  3. Thomas, Boston, 123456

and when the property is New York i want olny objects 1 and 2.

Does anyone has an idea how i can do it?

This is my code:

NSString *filterString = newsArticle;
NSPredicate *prediacte = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"Ort == '%@'",filterString]];
newsTownArray = [news filteredArrayUsingPredicate:predicate];

and when i come to the line:

cell.textLabel.text=[[newsTownArray objectAtIndex:indexPath.row] objectForKey:"Name"];
theandrew
  • 33
  • 5
  • possible duplicate of [filtering NSArray into a new NSArray in objective-c](http://stackoverflow.com/questions/110332/filtering-nsarray-into-a-new-nsarray-in-objective-c) – vikingosegundo Jan 21 '13 at 13:13

3 Answers3

4

You need to use NSPredicate for this.

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"town == 'New York'"];
[yourArray filterUsingPredicate:predicate];

Dynamically you can create predicate like:

NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"town == '%@'",yourInput]];

Here yourInput is a NSString which holds the required town name.

Please check these articles for more details:

  1. codeproject
  2. useyourloaf
Midhun MP
  • 103,496
  • 31
  • 153
  • 200
0

However you can do it within an array with the use of NSPredicate, but I will suggest to do bit differently, this will add up to your code and good programming way.

Create a custom class Person having these properties name, city and telephone.

Create an array that will store objects of Person.

After this you can manipulate/ filter / sort etc quite easily.


NSString *filterCity=@"Delhi";

NSMutableArray *yourArray=[NSMutableArray arrayWithArray:self.persons];
NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"city == '%@'",filterCity]];
[yourArray filterUsingPredicate:predicate];

NSLog(@"Filtered");
for (Person *per in yourArray) {
    NSLog(@"Name: %@, City: %@, Telephone: %@",per.name, per.city, per.telephone);

}
Anoop Vaidya
  • 46,283
  • 15
  • 111
  • 140
0

Use this code

NSMutableArray *subpredicates = [NSMutableArray array];

    for(NSString *term in arryOfWordsToBeSearched) {
        NSPredicate *p = [NSPredicate predicateWithFormat:@"self contains[cd] %@",term];
        [subpredicates addObject:p];
        }

     NSPredicate *filter = [NSCompoundPredicate andPredicateWithSubpredicates:subpredicates];
    result = (NSMutableArray*)[arryOfDummyData filteredArrayUsingPredicate: filter];
amar
  • 4,285
  • 8
  • 40
  • 52