开发者

Attach two NSMutableArrays and use with UISearchBar

开发者 https://www.devze.com 2023-02-25 01:27 出处:网络
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;

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
    Stac开发者_运维百科k         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.


One easy way I found is that to join the strings (name #nameID) and after that, seperate to get back nameID.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号