[英]Search in all objects of a NSArray of dictionaries
I have implemented the search method for a UITableView populate from a NSArray (mylist): 我已经从NSArray(mylist)实现了UITableView填充的搜索方法:
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope{
// reset array
[self.filteredListContent removeAllObjects];
// check the elements contained in the list
NSString *cellTitle;
for (cellTitle in myList){ //CHANGE HERE
NSComparisonResult result = [cellTitle compare:searchText options:NSCaseInsensitiveSearch range:NSMakeRange(0, [searchText length])];
if (result == NSOrderedSame){
[filteredListContent addObject:cellTitle];
}
}
}
Now i would the same method for search a char in objectForKey:@"name"
of a List of NSDictionary
: 现在,我将使用相同的方法搜索
objectForKey:@"name"
的char objectForKey:@"name"
NSDictionary
列表的objectForKey:@"name"
:
myList [0]:
{
gender
id
name
picture }
myList [1]
{
gender
id
name
picture }
I would something like this: 我会这样的:
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope{
[self.filteredFriendsList removeAllObjects];
NSString *cellTitle;
for (cellTitle in [[friendsList /* all objects */] objectForKey:@"name"]){
NSComparisonResult result = [cellTitle compare:searchText options:NSCaseInsensitiveSearch range:NSMakeRange(0, [searchText length])];
if (result == NSOrderedSame){
[filteredFriendsList addObject:cellTitle];
}
}
}
Someone has some ideas? 有人有想法吗? Thank you.
谢谢。
Why don't you just have the method do: 你为什么不让方法做到:
Friend *friend;
for (friend in friendsList) {
NSString *cellTitle = [friend objectForKey:@"name"];
/* do comparison */
}
Try this one: 试试这个:
for (NSString *name in [friendsList valueForKey:@"name"])
{
if ([name isEqualToString:searchText]) [filteredFriendsList addObject:name];
}
The key here is the fact that valueForKey:
method once invoked on an NSArray
it calls valueForKey:
on every of its objects. 这里的关键是
valueForKey:
方法一旦在NSArray
上调用它就会在每个对象上调用valueForKey:
Ps. PS。 If you want a case insensitive comparison you can do so like:
如果你想要一个不区分大小写的比较,你可以这样做:
NSComparisonResult res = [searchTex caseInsensitiveCompare:name];
if (res == NSOrderedSame) [filteredFriendsList addObject:name];
EDIT: (To include solution for substring matching) 编辑:(包括子串匹配的解决方案)
if ([name rangeOfString:searchText].location =! NSNotFound)
{
// 'name' contains 'searchText'
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.