Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter an NSArray which contains custom objects

I have UISearchBar, UITableView, a web service which returns a NSMutableArray that contain objects like this:

//Food.h
Food : NSObject { 
    NSString *foodName;
    int idFood;
}

@property (nonatomic, strong) NSString *foodName;

And the array:

Food *food1 = [Food alloc]initWithName:@"samsar" andId:@"1"];
Food *food2 = [Food alloc] initWithName:@"rusaramar" andId:@"2"];

NSSarray *array = [NSArray arrayWithObjects:food1, food2, nil];

How do I filter my array with objects with name beginning with "sa"?

like image 996
samir Avatar asked Mar 04 '12 20:03

samir


People also ask

What is NSArray Objective-C?

An object representing a static ordered collection, for use instead of an Array constant in cases that require reference semantics.

Can NSArray contain nil?

arrays can't contain nil. There is a special object, NSNull ( [NSNull null] ), that serves as a placeholder for nil.

Is NSArray ordered?

In Objective-C, arrays take the form of the NSArray class. An NSArray represents an ordered collection of objects. This distinction of being an ordered collection is what makes NSArray the go-to class that it is.


1 Answers

You can filter any array like you'd like to with the following code:

NSMutableArray *array = ...;

[array filterUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
    return [evaluatedObject.foodName hasPrefix:searchBar.text];
}];

This will filter the array "in-place" and is only accessible on an NSMutableArray. If you'd like to get a new array that's been filtered for you, use the filteredArrayUsingPredicate: NSArray method.

like image 165
Ash Furrow Avatar answered Nov 05 '22 21:11

Ash Furrow