简体   繁体   中英

Attach two NSMutableArrays and use with UISearchBar

I have two NSMutableArrays; name and nameID In my tableview, only name will be shown as textLabel.

I want to search names using UISearchBar. For example;

   name   --    nameID
    Stack         123
    Over          -1

nameID is the main thing needed to use.

So, is that possible to link two NSMutableArrays so that whenever users choose Stack, it shows 123?

Thanks

How about using one NSMutableDictionary with the names as the keys and the ids as the values?

Then, in your table, the data array can be found using [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] .

Bear in mind that allKeys and allValues return arrays whose order is not guaranteed.

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. 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.

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 . Now hold array of this object(say recordList ).

When we can search for any Record with given searchText as follows.

-(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`).

In future suppose you need to hold more details for Record than it will be easier.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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