我的应用程序从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来搜索我的数据(数组)。
我已经看过并阅读了教程,但我无法使用快速枚举或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];
}
不起作用......
如何实施搜索栏以搜索数据? 如何在搜索显示控制器中显示值和名称?
答案 0 :(得分:1)
你在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"];
并寻找必要的数组