Reputation: 630
Here's a bit of a newbie question.
I have a NSMutableDictionary *dict
which in the log looks like this:
"test1" = "5";
"test2" = "78";
"test3" = "343";
"test4" = "3";
I need to print each number by itself, but I'm pretty poor at arrays and FOR-sentences.
I was thinking something like:
for (dict) {
double number = [[[dict allKeys] objectAtIndex:0] doubleValue];
NSLog(@"Number: %f",number);
}
Which I want to look like this in the log on each line:
Number: 5
Number: 78
Number: 343
Number: 3
But obviously my "FOR"-method is gibberish.
Any help would be appreciated.
Upvotes: 1
Views: 1515
Reputation: 765
You use a fast enumeration for
to do this. It iterates over all the keys in the dictionary:
for (NSString *key in dict) {
double number = [[dict objectForKey:key] doubleValue];
NSLog(@"Number: %f", number);
}
Upvotes: 3
Reputation: 7633
As already mentioned fast-enumeration is preferable in these cases, but you could also do something like this:
for (int i =0; i<[dict count]; i++){
NSString *str=[dict objectForKey:[NSString stringWithFormat:@"test%d",i+1]];
NSLog(@"%@",str);
}
Upvotes: 0
Reputation: 112855
Using blocks:
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
@"5", @"test1",
@"78", @"test2",
@"343", @"test3",
@"3", @"test4",
nil];
[dictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSLog(@"Number: %@", obj);
}];
NSLog output:
Number: 5
Number: 3
Number: 343
Number: 78
Upvotes: 3
Reputation: 14886
The first answer has two objects being created with the name "number". Instead do:
for (NSString *key in dict) {
NSLog(@"Number as double: %f", [[dict objectForKey:key] doubleValue]);
NSLog(@"Number as string: %@", [dict objectForKey:key]);
}
What's great about fast enumeration is that it creates the object for you (and auto-release them). The key
is what's being given to you when fast-enumerating through NSDictionaries. Because you now have the key, you just grab the objectAtKey. In your case, it's a string in your dictionary, so you'll have to either convert it to a double (or whatever type you need), or output as a string. I added examples for both cases above. Good luck!
Upvotes: 0
Reputation: 14169
If you just want to log these numbers, try the following:
for (NSString *number in dict) {
NSLog(@"Number: %@",[dict objectForKey:number]);
}
Upvotes: 0