views:

284

answers:

1

I am trying to filter a NSMutableArray. Search array for items by certain country. I have tried NSpredicate which works great however I need to re-use the original array which I cannot with NSpredicate. So I am trying the below code.

Q. What is the best way to filter an NSMutableArray keeping the original array intact?

//The following code works

filteredArray = [[NSMutableArray alloc] init];

unsigned int i;

for (i = 0; i < [appDelegate.arrayToBeFiltered count]; i++) {

id session = [appDelegate.ads objectAtIndex: i];

id Country = [[appDelegate.arrayToBeFiltered objectAtIndex: i] TheCountry];

[filteredArray addObject: session];

//However when I add the if statement as below I get index beyond bounds

filteredArray = [[NSMutableArray alloc] init];

unsigned int i;

for (i = 0; i < [appDelegate.arrayToBeFiltered count]; i++) {

id session = [appDelegate.ads objectAtIndex: i];

id Country = [[appDelegate.arrayToBeFiltered objectAtIndex: i] TheCountry];

if (Country == @"United States"){ [filteredArray addObject: session]; }

A: 

Use - (NSArray *)filteredArrayUsingPredicate:(NSPredicate *)predicate

As a side-note, in the code above you probably mean to do this [Country isEqualToString: @"United States"]

As an extra side note - don't capitalise variables and method names. Just a style thing but capitalisation is usually reserved for Class names

That worked great thanks. PS I will adjust the style thing.
ppm7