从 NSMutableDictionary 获取 objectAtIndex
Get objectAtIndex from NSMutableDictionary
在我的应用程序中,我正在使用 UISearchBar
,用户将通过使用用户名搜索从 NSMutableArray
进行搜索。这是我从 NSMutableArray
搜索用户的方法
- (void)searchTableList
{
NSString *searchString = searchBar.text;
NSMutableArray *searchArray = [[NSMutableArray alloc] init];
for (NSDictionary *dictionary in contentList)
{
NSArray *array = [dictionary objectForKey:@"username"];
[searchArray addObject:array];
}
for (NSString *sTemp in searchArray)
{
NSRange titleResultsRange = [sTemp rangeOfString:searchString options:NSCaseInsensitiveSearch];
if (titleResultsRange.length > 0)
[filteredContentList addObject:sTemp];
}
}
下面是我如何配置 UITableView
以显示搜索结果
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"SearchListTableViewCell";
NSMutableDictionary *dict=[contentList objectAtIndex:indexPath.row];
SearchListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil)
{
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"SearchListTableViewCell" owner:nil options:nil];
cell = (SearchListTableViewCell*)[topLevelObjects objectAtIndex:0];
cell.backgroundColor=[UIColor colorWithRed:239.0/255 green:239.0/255 blue:239.0/255 alpha:1];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
}
// Configure the cell...
if (isSearching)
{
cell.friendName.text = [filteredContentList objectAtIndex:indexPath.row];
NSMutableArray *searchImageArray=[[NSMutableArray alloc]init];
for (NSDictionary *dictionary in contentList)
{
NSArray *imageArray=[dictionary objectForKey:@"thumbnail_path_150_150"];
NSLog(@"image arrayt is %@",imageArray);
[searchImageArray addObject:imageArray];
}
for (NSString *imageS in searchImageArray) {
NSRange title=[imageS rangeOfString:cell.friendName.text options:NSCaseInsensitiveSearch];
if (title.length>0) {
[filteredImage addObject:imageS];
}
}
NSString *url=[NSString stringWithFormat:@"%@/get_image?avatar=%@",BaseURL,[filteredImage objectAtIndex:indexPath.row]];
url=[url stringByReplacingOccurrencesOfString:@"\" withString:@"/"];
UIImage* myImage = [UIImage imageWithData:
[NSData dataWithContentsOfURL:
[NSURL URLWithString:url]]];
[cell.friendProfileImage setImage:myImage];
NSLog(@"filtered Image data %lu",(unsigned long)filteredImage.count);
NSLog(@"filtered content list data %lu",(unsigned long)filteredContentList.count);
}
else
{
cell.friendName.text =[dict objectForKey:@"username"];
NSString *url=[NSString stringWithFormat:@"%@/get_image?avatar=%@",BaseURL,[dict objectForKey:@"thumbnail_path_150_150"]];
url=[url stringByReplacingOccurrencesOfString:@"\" withString:@"/"];
UIImage* myImage = [UIImage imageWithData:
[NSData dataWithContentsOfURL:
[NSURL URLWithString:url]]];
[cell.friendProfileImage setImage:myImage];
}
return cell;
}
现在我想从NSMutableDictionary
中获取搜索到的用户名的其余数据。这是我的字典。
(
{
jid = "hey@196.0.0.1";
"thumbnail_path_150_150" = "E\path\to\getImage\files\heythumbnail";
username = hey;
},
{
jid = "tweety@196.0.0.1";
"thumbnail_path_150_150" = "E:\path\to\getImage\files\tweetythumbnail";
username = tweety;
}
)
这里我想获取搜索用户的图片。如果用户搜索嘿,它必须在 tableViewCell 上显示 "thumbnail_path_150_150"
="E\path\to\getImage\files\heythumbnail";
此图像。我尝试了设置图像的代码但是当两个用户具有相同的名称时它会替换图像。就像如果一个用户是 Ray 而另一个用户是 Blueray ,那么它会改变两者的形象。我知道我写的太多了。但在这一点上我真的很困惑。请任何人帮助解决这个问题。
应用 NSPredicate
过滤您的数组,然后使用此数组填充 tableView
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"username contains[c] %@",_search_bar.text];
NSArray *filteredArray = [yourMainArray filteredArrayUsingPredicate:predicate];
NSLog(@"here is the filteredCandyArray%@",filteredCandyArray);
//set it to the array you use to fill the table
_dataSourceArray = _filteredCandyArray;
//go!
[_yourTable reloadData];
默认情况下,字符串比较区分大小写和变音符号。您可以使用方括号内的关键字符 c 和 d 修改运算符,以分别指定不区分大小写和变音符号,例如 firstName BEGINSWITH[cd] $FIRST_NAME.
BEGINSWITH:左边的表达式从右边的表达式开始。
CONTAINS:左边的表达式包含右边的表达式。
ENDSWITH:左边的表达式以右边的表达式结束。
LIKE:左边的表达式等于右边的表达式:?和 * 允许作为通配符,其中 ?匹配 1 个字符,* 匹配 0 个或多个字符。
匹配:左手表达式等于右手表达式。
或更多详情请访问 http://nshipster.com/nspredicate/
最简单的方法是使用谓词,稍微修改一下代码就可以像这样
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"username == %@", @"ray"];
NSArray *searchedArray = [rootArray filteredArrayUsingPredicate:predicate];
上面的代码只会 return 用户名是 ray 而不是 Ray 或 RAY 等的值
我建议您使用 Search Bar and Search Display Controller
而不是 Search Bar
。
另外看看下面的代码,它涵盖了你想要的一切。
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
#pragma mark
#pragma mark - View Lifecycle
-(void)viewDidLoad
{
[super viewDidLoad];
NSDictionary *dic1 = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"1", @"India", @"IN", @"+91", nil] forKeys:[NSArray arrayWithObjects:@"CountryId", @"CountryName", @"CountryCode", @"ISDCode", nil]];
NSDictionary *dic2 = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"2", @"Australia", @"AU", @"+61", nil] forKeys:[NSArray arrayWithObjects:@"CountryId", @"CountryName", @"CountryCode", @"ISDCode", nil]];
NSDictionary *dic3 = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"3", @"New Zealand", @"NZ", @"+64", nil] forKeys:[NSArray arrayWithObjects:@"CountryId", @"CountryName", @"CountryCode", @"ISDCode", nil]];
NSDictionary *dic4 = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"4", @"South Africa", @"SA", @"+27", nil] forKeys:[NSArray arrayWithObjects:@"CountryId", @"CountryName", @"CountryCode", @"ISDCode", nil]];
NSDictionary *dic5 = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"5", @"England", @"EN", @"+44", nil] forKeys:[NSArray arrayWithObjects:@"CountryId", @"CountryName", @"CountryCode", @"ISDCode", nil]];
NSDictionary *dic6 = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"6", @"Israel", @"IS", @"+972", nil] forKeys:[NSArray arrayWithObjects:@"CountryId", @"CountryName", @"CountryCode", @"ISDCode", nil]];
NSDictionary *dic7 = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"7", @"Afghanistan", @"AF", @"+93", nil] forKeys:[NSArray arrayWithObjects:@"CountryId", @"CountryName", @"CountryCode", @"ISDCode", nil]];
NSDictionary *dic8 = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"8", @"Ireland", @"IR", @"+353", nil] forKeys:[NSArray arrayWithObjects:@"CountryId", @"CountryName", @"CountryCode", @"ISDCode", nil]];
NSDictionary *dic9 = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"9", @"China", @"CN", @"+86", nil] forKeys:[NSArray arrayWithObjects:@"CountryId", @"CountryName", @"CountryCode", @"ISDCode", nil]];
arrTotalCountries = [NSArray arrayWithObjects:dic1, dic2, dic3, dic4, dic5, dic6, dic7, dic8, dic9, nil];
}
#pragma mark
#pragma mark - UITableView delegate, datasource methods
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if(tableView == self.searchDisplayController.searchResultsTableView){
return [arrFilteredCountries count];
}
else{
return [arrTotalCountries count];
}
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier = [NSString stringWithFormat:@"CellIdentifier%ld%ld",(long)indexPath.section,(long)indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSDictionary *dicCountry;
if (tableView == self.searchDisplayController.searchResultsTableView) {
dicCountry = [arrFilteredCountries objectAtIndex:indexPath.row];
} else {
dicCountry = [arrTotalCountries objectAtIndex:indexPath.row];
}
NSString *strShow = [NSString stringWithFormat:@"%@ (%@)",[dicCountry objectForKey:@"CountryName"],[dicCountry objectForKey:@"ISDCode"]];
cell.textLabel.text = strShow;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSDictionary *dicCountry;
if (tableView == self.searchDisplayController.searchResultsTableView) {
dicCountry = [arrFilteredCountries objectAtIndex:indexPath.row];
} else {
dicCountry = [arrTotalCountries objectAtIndex:indexPath.row];
}
NSString *countryName = [dicCountry objectForKey:@"CountryName"];
NSString *CountryISDCode = [dicCountry objectForKey:@"ISDCode"];
[self showAlertWithTitle:countryName message:CountryISDCode];
}
#pragma mark
#pragma mark - Other method Implementation
-(void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(SELF.CountryName BEGINSWITH[cd] %@) OR (SELF.ISDCode CONTAINS[cd] %@)", searchText, searchText];
arrFilteredCountries = [arrTotalCountries filteredArrayUsingPredicate:predicate];
}
-(void)showAlertWithTitle:(NSString *)title message:(NSString *)message
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:message delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
}
#pragma mark
#pragma mark - UISearchbar controller delegate
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString
scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
objectAtIndex:[self.searchDisplayController.searchBar
selectedScopeButtonIndex]]];
return YES;
}
#pragma mark
#pragma mark - Memory management
-(void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
@end
另外添加评论,以防有人卡在某个点上。我已经实现了这个并且效果很好。这是将搜索功能添加到您的 Table 视图的一种简短且最佳的方法。
在我的应用程序中,我正在使用 UISearchBar
,用户将通过使用用户名搜索从 NSMutableArray
进行搜索。这是我从 NSMutableArray
- (void)searchTableList
{
NSString *searchString = searchBar.text;
NSMutableArray *searchArray = [[NSMutableArray alloc] init];
for (NSDictionary *dictionary in contentList)
{
NSArray *array = [dictionary objectForKey:@"username"];
[searchArray addObject:array];
}
for (NSString *sTemp in searchArray)
{
NSRange titleResultsRange = [sTemp rangeOfString:searchString options:NSCaseInsensitiveSearch];
if (titleResultsRange.length > 0)
[filteredContentList addObject:sTemp];
}
}
下面是我如何配置 UITableView
以显示搜索结果
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"SearchListTableViewCell";
NSMutableDictionary *dict=[contentList objectAtIndex:indexPath.row];
SearchListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil)
{
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"SearchListTableViewCell" owner:nil options:nil];
cell = (SearchListTableViewCell*)[topLevelObjects objectAtIndex:0];
cell.backgroundColor=[UIColor colorWithRed:239.0/255 green:239.0/255 blue:239.0/255 alpha:1];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
}
// Configure the cell...
if (isSearching)
{
cell.friendName.text = [filteredContentList objectAtIndex:indexPath.row];
NSMutableArray *searchImageArray=[[NSMutableArray alloc]init];
for (NSDictionary *dictionary in contentList)
{
NSArray *imageArray=[dictionary objectForKey:@"thumbnail_path_150_150"];
NSLog(@"image arrayt is %@",imageArray);
[searchImageArray addObject:imageArray];
}
for (NSString *imageS in searchImageArray) {
NSRange title=[imageS rangeOfString:cell.friendName.text options:NSCaseInsensitiveSearch];
if (title.length>0) {
[filteredImage addObject:imageS];
}
}
NSString *url=[NSString stringWithFormat:@"%@/get_image?avatar=%@",BaseURL,[filteredImage objectAtIndex:indexPath.row]];
url=[url stringByReplacingOccurrencesOfString:@"\" withString:@"/"];
UIImage* myImage = [UIImage imageWithData:
[NSData dataWithContentsOfURL:
[NSURL URLWithString:url]]];
[cell.friendProfileImage setImage:myImage];
NSLog(@"filtered Image data %lu",(unsigned long)filteredImage.count);
NSLog(@"filtered content list data %lu",(unsigned long)filteredContentList.count);
}
else
{
cell.friendName.text =[dict objectForKey:@"username"];
NSString *url=[NSString stringWithFormat:@"%@/get_image?avatar=%@",BaseURL,[dict objectForKey:@"thumbnail_path_150_150"]];
url=[url stringByReplacingOccurrencesOfString:@"\" withString:@"/"];
UIImage* myImage = [UIImage imageWithData:
[NSData dataWithContentsOfURL:
[NSURL URLWithString:url]]];
[cell.friendProfileImage setImage:myImage];
}
return cell;
}
现在我想从NSMutableDictionary
中获取搜索到的用户名的其余数据。这是我的字典。
(
{
jid = "hey@196.0.0.1";
"thumbnail_path_150_150" = "E\path\to\getImage\files\heythumbnail";
username = hey;
},
{
jid = "tweety@196.0.0.1";
"thumbnail_path_150_150" = "E:\path\to\getImage\files\tweetythumbnail";
username = tweety;
}
)
这里我想获取搜索用户的图片。如果用户搜索嘿,它必须在 tableViewCell 上显示 "thumbnail_path_150_150"
="E\path\to\getImage\files\heythumbnail";
此图像。我尝试了设置图像的代码但是当两个用户具有相同的名称时它会替换图像。就像如果一个用户是 Ray 而另一个用户是 Blueray ,那么它会改变两者的形象。我知道我写的太多了。但在这一点上我真的很困惑。请任何人帮助解决这个问题。
应用 NSPredicate
过滤您的数组,然后使用此数组填充 tableView
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"username contains[c] %@",_search_bar.text];
NSArray *filteredArray = [yourMainArray filteredArrayUsingPredicate:predicate];
NSLog(@"here is the filteredCandyArray%@",filteredCandyArray);
//set it to the array you use to fill the table
_dataSourceArray = _filteredCandyArray;
//go!
[_yourTable reloadData];
默认情况下,字符串比较区分大小写和变音符号。您可以使用方括号内的关键字符 c 和 d 修改运算符,以分别指定不区分大小写和变音符号,例如 firstName BEGINSWITH[cd] $FIRST_NAME.
BEGINSWITH:左边的表达式从右边的表达式开始。 CONTAINS:左边的表达式包含右边的表达式。 ENDSWITH:左边的表达式以右边的表达式结束。 LIKE:左边的表达式等于右边的表达式:?和 * 允许作为通配符,其中 ?匹配 1 个字符,* 匹配 0 个或多个字符。 匹配:左手表达式等于右手表达式。 或更多详情请访问 http://nshipster.com/nspredicate/
最简单的方法是使用谓词,稍微修改一下代码就可以像这样
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"username == %@", @"ray"];
NSArray *searchedArray = [rootArray filteredArrayUsingPredicate:predicate];
上面的代码只会 return 用户名是 ray 而不是 Ray 或 RAY 等的值
我建议您使用 Search Bar and Search Display Controller
而不是 Search Bar
。
另外看看下面的代码,它涵盖了你想要的一切。
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
#pragma mark
#pragma mark - View Lifecycle
-(void)viewDidLoad
{
[super viewDidLoad];
NSDictionary *dic1 = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"1", @"India", @"IN", @"+91", nil] forKeys:[NSArray arrayWithObjects:@"CountryId", @"CountryName", @"CountryCode", @"ISDCode", nil]];
NSDictionary *dic2 = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"2", @"Australia", @"AU", @"+61", nil] forKeys:[NSArray arrayWithObjects:@"CountryId", @"CountryName", @"CountryCode", @"ISDCode", nil]];
NSDictionary *dic3 = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"3", @"New Zealand", @"NZ", @"+64", nil] forKeys:[NSArray arrayWithObjects:@"CountryId", @"CountryName", @"CountryCode", @"ISDCode", nil]];
NSDictionary *dic4 = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"4", @"South Africa", @"SA", @"+27", nil] forKeys:[NSArray arrayWithObjects:@"CountryId", @"CountryName", @"CountryCode", @"ISDCode", nil]];
NSDictionary *dic5 = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"5", @"England", @"EN", @"+44", nil] forKeys:[NSArray arrayWithObjects:@"CountryId", @"CountryName", @"CountryCode", @"ISDCode", nil]];
NSDictionary *dic6 = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"6", @"Israel", @"IS", @"+972", nil] forKeys:[NSArray arrayWithObjects:@"CountryId", @"CountryName", @"CountryCode", @"ISDCode", nil]];
NSDictionary *dic7 = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"7", @"Afghanistan", @"AF", @"+93", nil] forKeys:[NSArray arrayWithObjects:@"CountryId", @"CountryName", @"CountryCode", @"ISDCode", nil]];
NSDictionary *dic8 = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"8", @"Ireland", @"IR", @"+353", nil] forKeys:[NSArray arrayWithObjects:@"CountryId", @"CountryName", @"CountryCode", @"ISDCode", nil]];
NSDictionary *dic9 = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"9", @"China", @"CN", @"+86", nil] forKeys:[NSArray arrayWithObjects:@"CountryId", @"CountryName", @"CountryCode", @"ISDCode", nil]];
arrTotalCountries = [NSArray arrayWithObjects:dic1, dic2, dic3, dic4, dic5, dic6, dic7, dic8, dic9, nil];
}
#pragma mark
#pragma mark - UITableView delegate, datasource methods
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if(tableView == self.searchDisplayController.searchResultsTableView){
return [arrFilteredCountries count];
}
else{
return [arrTotalCountries count];
}
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier = [NSString stringWithFormat:@"CellIdentifier%ld%ld",(long)indexPath.section,(long)indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSDictionary *dicCountry;
if (tableView == self.searchDisplayController.searchResultsTableView) {
dicCountry = [arrFilteredCountries objectAtIndex:indexPath.row];
} else {
dicCountry = [arrTotalCountries objectAtIndex:indexPath.row];
}
NSString *strShow = [NSString stringWithFormat:@"%@ (%@)",[dicCountry objectForKey:@"CountryName"],[dicCountry objectForKey:@"ISDCode"]];
cell.textLabel.text = strShow;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSDictionary *dicCountry;
if (tableView == self.searchDisplayController.searchResultsTableView) {
dicCountry = [arrFilteredCountries objectAtIndex:indexPath.row];
} else {
dicCountry = [arrTotalCountries objectAtIndex:indexPath.row];
}
NSString *countryName = [dicCountry objectForKey:@"CountryName"];
NSString *CountryISDCode = [dicCountry objectForKey:@"ISDCode"];
[self showAlertWithTitle:countryName message:CountryISDCode];
}
#pragma mark
#pragma mark - Other method Implementation
-(void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(SELF.CountryName BEGINSWITH[cd] %@) OR (SELF.ISDCode CONTAINS[cd] %@)", searchText, searchText];
arrFilteredCountries = [arrTotalCountries filteredArrayUsingPredicate:predicate];
}
-(void)showAlertWithTitle:(NSString *)title message:(NSString *)message
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:message delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
}
#pragma mark
#pragma mark - UISearchbar controller delegate
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString
scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
objectAtIndex:[self.searchDisplayController.searchBar
selectedScopeButtonIndex]]];
return YES;
}
#pragma mark
#pragma mark - Memory management
-(void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
@end
另外添加评论,以防有人卡在某个点上。我已经实现了这个并且效果很好。这是将搜索功能添加到您的 Table 视图的一种简短且最佳的方法。