过滤包含自定义对象的NSArray [英] Filter an NSArray which contains custom objects
本文介绍了过滤包含自定义对象的NSArray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有 UISearchBar
, UITableView
,一个返回 NSMutableArray的网络服务
包含如下对象:
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;
数组:
Food *food1 = [Food alloc]initWithName:@"samsar" andId:@"1"];
Food *food2 = [Food alloc] initWithName:@"rusaramar" andId:@"2"];
NSSarray *array = [NSArray arrayWithObjects:food1, food2, nil];
如何使用名称以sa开头的对象过滤我的数组?
How do I filter my array with objects with name beginning with "sa"?
推荐答案
您可以使用以下代码过滤任何您想要的数组:
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];
}];
这将就地过滤数组,只能在的NSMutableArray
。如果您想获得一个已经过滤的新数组,请使用 filteredArrayUsingPredicate:
NSArray
方法。
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.
这篇关于过滤包含自定义对象的NSArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文