Andrew Johnson
Andrew Johnson

Reputation: 13286

Why aren't the values being stored to the NSDictionary?

See the log statement comments at the end of the code snippet... acceleration.x is a decimal, but when I store it to the dict, it seems to be 0.

NSDictionary *entry = [NSDictionary dictionaryWithObjectsAndKeys:
  [NSNumber numberWithDouble:acceleration.x], @"x",
  [NSNumber numberWithDouble:acceleration.y], @"y",
  [NSNumber numberWithDouble:acceleration.z], @"z",
  [NSDate date], @"date",
   nil];
[self.accelerometerArray addObject: entry];
//this logs a decimal number as expected
NSLog(@"Acceleration.x: %g", acceleration.x);
//this logs a 0 :(
NSLog(@"Accel Array X: %g", [entry objectForKey: @"x"]);

Upvotes: 0

Views: 612

Answers (1)

Alex Rozanski
Alex Rozanski

Reputation: 38005

When you call:

[entry objectForKey: @"x"]

You are returned the NSNumber instance and not the double value. Change that line to:

NSLog(@"Accel Array X: %g", [[entry objectForKey: @"x"] doubleValue]);

You wouldn't be able to retrieve a double from an NSDictionary directly because keys and values can only be objects, not primitive types.

Upvotes: 3

Related Questions