views:

45

answers:

1

I have an NSDictionary where both the keys and values are NSStrings and I'd like to create one NSString from them in the form of

Key1: Value1
Key2: Value2

What is the best method of doing this?

+5  A: 

Lets assume your dictionary is called myDict and key is the value of the key you are looking for

[NSString stringWithFormat:@"%@: %@", key, [myDict objectForKey: key]];

This will return

Key: Value

Of course if this is just for you logging on the console you can make life easier for yourself and do something like

NSLog(@"%@", [myDict description]);

Edit::

To display the entire dictionary you can use a for each loop thusly:

NSMutableString *finalString = [NSMutableString string];

for(NSString *key in [myDict allKeys]){

    [finalString appendFormat:@"%@: %@\n", key, [myDict objectForKey: key]];

}
James Raybould
@James: Just `NSLog(@"%@", myDict);` is enough, the `-description` will be called automatically.
KennyTM
When reading it back though at a later date I always find it easier to understand exactly whats happening when I use [myDict description] over myDict. I guess its just my personal preference!
James Raybould
This it not quite what I was after, I want one string that will be displayed on-screen which contains the whole of the dictionary in the Key: Value format.
David Reynolds
I've edited my answer so that it outputs like in your quick example, all it does it iterate over all the keys in the dictionary and appends them to the back of a mutable string with a certain format
James Raybould
Yep, that was exactly what I was after, thanks!
David Reynolds