Iphone – Creating an NSDictionary


In the following code, the first log statement shows a decimal as expected, but the second logs NULL. What am I doing wrong?

NSDictionary *entry = [[NSDictionary alloc] initWithObjectsAndKeys:
  @"x", [NSNumber numberWithDouble:acceleration.x],
  @"y", [NSNumber numberWithDouble:acceleration.y],
  @"z", [NSNumber numberWithDouble:acceleration.z],
  @"date", [NSDate date],
NSLog([NSString stringWithFormat:@"%@", [NSNumber numberWithDouble:acceleration.x]]);
NSLog([NSString stringWithFormat:@"%@", [entry objectForKey:@"x"]]);

Best Solution

You are exchanging the order in which you insert objects and key: you need to insert first the object, then the key as shown in the following example.

NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:@"value1", @"key1", @"value2", @"key2", nil];
Related Question