Filter an NSArray which contains custom objects

北战南征 提交于 2019-12-18 12:02:15

问题


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"?


回答1:


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.




回答2:


NSString *predString = [NSString stringWithFormat:@"(foodName BEGINSWITH[cd] '%@')", @"sa"];

NSPredicate *pred = [NSPredicate predicateWithFormat:predString];

NSArray *array = [arr filteredArrayUsingPredicate:pred];
NSLog(@"%@", array);


来源:https://stackoverflow.com/questions/9558335/filter-an-nsarray-which-contains-custom-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!