Key- Value Table help required

Discussion in 'iOS Programming' started by sagarshivam, Aug 29, 2011.

  1. sagarshivam, Aug 29, 2011
    Last edited by a moderator: Aug 29, 2011

    sagarshivam macrumors member

    Joined:
    May 24, 2011
    #1
    Hi all!!

    I am looking for some data structure which will store data in terms of key and value and where one key corresponds to one or more than one value.

    So , something like:

    KEY VALUE
    key1 value1
    key1 value2
    key1 value3
    key2 value4
    key2 value5
    ...... ..........

    and on query all VALUE for a particular KEY is obtained in array.

    I tried implementing NSDictionary but I am able to save on one to one basis only Multiple values for one ley is not possible.

    Kindly help

    or say that I have three keys (string type)like: key1,key2 and key3 and corresponding to each I have three arrays (NSarray type) array1, array2 and array3

    So i want to map these as key and values:


    key1 ---------> array1
    key2----------> array2
    key3----------> array3

    So that from this structure, whenever VALUE for KEY (say key1) is queried, array1 (and so on) is returned.
     
  2. jiminaus macrumors 65816

    jiminaus

    Joined:
    Dec 16, 2010
    Location:
    Sydney
    #2
    Store the NSArray/NSMutableArray as the value in the dictionary.
     
  3. RonC macrumors regular

    Joined:
    Oct 18, 2007
    Location:
    Chicago-area
    #3
    multiset in STL?

    Ok, so how do you use this thing? Is it set up statically at the beginning (of something) and then accessed by key to get that array? Is it dynamically created, where things get added (by key) to the arrays? The former is what jiminaus posted. The latter might be better done by defining your own class either as a subclass of NSMutableDictionary (or uses a NSMutableDictionary) to stores NSMutableArrays in the dictionary.

    That's reasonably straightforward. Modify the setObject:forKey to append the object to current result of the objectForKey: (if there is one) or create a new NSMutableArray if there isn't one. Create new methods for other operations (if you want to delete an object from one of the arrays, you could define a removeObject:forKey: method).

    I'm not sure why the documentation recommends against subclassing, but for a simple specialization like you describe it seems pretty safe.

    <100 lines of code, 2 files, depending on how many operations you need.
     
  4. jiminaus macrumors 65816

    jiminaus

    Joined:
    Dec 16, 2010
    Location:
    Sydney
    #4
    Not, it's not safe. NSDictionary is a class cluster.
     

Share This Page