gpt4 book ai didi

ios - 使用快速枚举或 NSPredicate 在数组中搜索(从带有字典的 plist)

转载 作者:行者123 更新时间:2023-11-29 13:09:09 26 4
gpt4 key购买 nike

我的应用程序从 plist 文件中读取数据并在 UITableView 中显示数据

我的 plist 示例:

<array>
<dict>
<key>name</key>
<string>One</string>
<key>value</key>
<string>1</string>
</dict>
<dict>
<key>name</key>
<string>Two</string>
<key>value</key>
<string>2</string>
</dict>
<dict>
<key>name</key>
<string>Three</string>
<key>value</key>
<string>3</string>
</dict>
<dict>
<key>name</key>
<string>Four</string>
<key>value</key>
<string>4</string>
</dict>
<dict>
<key>name</key>
<string>Five</string>
<key>value</key>
<string>5</string>
</dict>
<dict>
<key>name</key>
<string>Six</string>
<key>value</key>
<string>6</string>
</dict>
</array

现在一切正常。一切都显示在我的 TableView 中,并带有正确的详细单元格。我在 detailTextLabel 中显示值,在 TextLabel 中显示名称。

if (isSearching==true) {
cell.textLabel.text = [searchArray objectAtIndex:indexPath.row];
//How to include the key "value" from this non-dictionary Array?
return cell;
}

cell.textLabel.text = [[mainArray objectAtIndex:indexPath.row] objectForKey:@"name"];
cell.detailTextLabel.text = [[mainArray objectAtIndex:indexPath.row] objectForKey:@"value"];

当然还有 numbersOfRowsInSection :

if (isSearching) {
return [searchArray count];
}
return [IDarray count];

我正在使用它从 plist 中获取一个数组:

NSMutableArray *mainArray = [[NSMutableArray alloc] initWithContentsOfFile:path-to-plist-file];

但后来我想添加一个 UISearchBar 来搜索我的数据(数组)。

我已经看过并阅读了教程,但我无法让它与 Fast Enumeration 或 NSPredicate 一起使用,还有更多选择吗?

因为我正在从包含许多词典的 plist 中读取数据?

到目前为止我没有成功测试过:

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
if (searchText.length==0) {
isSearching = false;
}

else {
isSearching=true;
searchArray = [[NSArray alloc]init];

NSPredicate *pre = [NSPredicate predicateWithFormat:@"SELF contains [search] %@", searchText];
searchArray = [mainArray filteredArrayUsingPredicate:pre];
}
[tableView reloadData];
}

这会在搜索时显示“无结果”,有时会崩溃。

我也测试过:

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
if (searchText.length==0) {
isSearching = false;
}

else {
isSearching=true;
searchArray = [[NSArray alloc]init];

for (NSString *str in mainArray) {
NSRange searchRange = [str rangeOfString:searchText options:NSCaseInsensitiveSearch];


if (searchRange.location !=NSNotFound) {
[searchArray addObject:str];
}
}
[tableView reloadData];
}

不工作...

如何实现搜索栏来搜索数据?以及如何在搜索显示 Controller 中显示值和名称?

最佳答案

您在 mainArray 中有字典数组。它不起作用:

for (NSString *str in mainArray)

试试看:

id mainArray = [[NSMutableArray alloc] initWithContentsOfFile:path-to-plist-file];
NSMutableArray *names = [mainArray valueForKey:@"name"];
NSMutableArray *values = [mainArray valueForKey:@"value"];

并在必要的数组中寻找

关于ios - 使用快速枚举或 NSPredicate 在数组中搜索(从带有字典的 plist),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17812937/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com