0

I have the following array of arrays ::

<array>
    <dict>
        <key>aa</key>
        <string>2012-07-19 11:16:00</string>
    </dict>
    <dict>
        <key>bb</key>
        <string>2012-07-19 11:16:02</string>
    </dict>
    <dict>
        <key>cc</key>
        <string>2012-07-19 11:16:05</string>
    </dict>
</array>

The name of this array is abcd and it is NSMutable.

I want to add a new dict element into this array, say with key value of aa and some other string value. I want to check if this new key value already exists as a key for some dict element. How can I do that ?? Can someone help me out ?? Thanks and Regards.

4
  • 1
    Wouldn't it be easier to store your data as a dictionary rather than an array of key-value pairs? Commented Jul 19, 2012 at 7:31
  • You mean you have an array of dictionaries, not an array of arrays.. can't you just insert the key-value pairs of all the dictionaries in your array into a single separate dictionary? Now your array of dictionaries has simply become a single dictionary, so you can check for an existent key, or update the value corresponding to a preexisting key simply by adding the key-value pair to the dictionary (if that's what you want). [If the order of the dictionaries in the array was important, you can keep track of that separately, and reconstruct your array of dictionaries again if need be] Commented Jul 19, 2012 at 7:34
  • I actually dont know what code to write .. I wud prefer having a single dictionary.. can you write some code into the answer .. I am new to objective C. Commented Jul 19, 2012 at 7:57
  • Take a look at The Developer Docs. Once you understand the difference between the collection classes and when to use one or the other, implementing will be easy. Commented Jul 19, 2012 at 9:13

1 Answer 1

1

Say arr is your NSMutableArray and dictToBeAdded is your dictionary to be added. And let strKey is the key for this dictionary :

for(int i=0;i<[arr count];i++)
{
    NSMutableDictionary *dict = [arr objectAtIndex:i];
    for(NSString *str in [dict allKeys])
    {
         if(![str isEqualToString:strKey])
             [arr addObject:dict];
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

where should I declare strKey and how ? Thanks.
I have taken strKey just for reference. It is the key of the dictionary you want to have. eg if you are adding vv and its value, then vv is strKey.
No need to declare it. Just replace strKey by the string you are using as key.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.