简体   繁体   English

附加两个NSMutableArrays并与UISearchBar一起使用

[英]Attach two NSMutableArrays and use with UISearchBar

I have two NSMutableArrays; 我有两个NSMutableArrays; name and nameID In my tableview, only name will be shown as textLabel. name和nameID在我的表视图中,只有名称将显示为textLabel。

I want to search names using UISearchBar. 我想使用UISearchBar搜索名称。 For example; 例如;

   name   --    nameID
    Stack         123
    Over          -1

nameID is the main thing needed to use. nameID是需要使用的主要内容。

So, is that possible to link two NSMutableArrays so that whenever users choose Stack, it shows 123? 那么,是否可以链接两个NSMutableArrays,以便每当用户选择Stack时,它都显示123?

Thanks 谢谢

How about using one NSMutableDictionary with the names as the keys and the ids as the values? 如何使用一个NSMutableDictionary以名称作为键,将ids作为值?

Then, in your table, the data array can be found using [myNameDict allKeys] . 然后,在您的表中,可以使用[myNameDict allKeys]找到数据数组。

Or, you can make the id's the keys and the names the values, in which case, all the names would be accessible as an array by calling [myNameDict allValues] . 或者,您可以使id为键,为名称命名为值,在这种情况下,可以通过调用[myNameDict allValues]将所有名称作为数组访问。

Bear in mind that allKeys and allValues return arrays whose order is not guaranteed. 请记住, allKeysallValues返回不保证顺序的数组。

So, you could, as a third option, maintain an array of dictionaries, where each dictionary has two keys, name and id, whose values are the name and id. 因此,作为第三个选择,您可以维护一个词典数组,其中每个词典都有两个键:name和id,其值分别是name和id。 Then you've paired each name and id into a single object (a dictionary) and you can be assured of the order of your array of name/id pairs. 然后,将每个名称和ID配对到一个对象(一个字典)中,就可以确定名称/ ID对数组的顺序。

One approach could be like this, rather than maintaining data separately as they bear relationship you can encapsulate them in a class say Record which has two fields name and id . 一种方法可能是这样的,而不是单独维护数据,因为它们具有关系,您可以将它们封装在一个类中,称为Record ,该类具有两个字段nameid Now hold array of this object(say recordList ). 现在保存此对象的数组(例如recordList )。

When we can search for any Record with given searchText as follows. 当我们可以使用给定的searchText搜索任何Record时,如下所示。

-(Record *) searchRecordWithName:(NSString *)searchText
{
Record *tempRecord;
  for( tempRecord in recordList)
  {
    NSRange searchRange = [tempRecord.name rangeOfString:searchText options:NSCaseInsensitiveSearch];
     if( searchRange.length>0 && searchRange.location==0)
      {
         break;
      }
  }
return tempRecord;
}

Please correct the above code as per your need. 请根据您的需要更正上面的代码。 Here I am considering you want to find nameId for record having name starting with searchText(as you see I have used searchRange.location ==0`). 在这里,我正在考虑您要查找名称以searchText开头的record nameId(如您所见,我使用了searchRange.location == searchRange.location )。

In future suppose you need to hold more details for Record than it will be easier. 将来,假设您需要保存“记录”的更多详细信息,这将比以前更容易。

我发现一种简单的方法是连接字符串(名称#nameID),然后分开获取名称ID。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM