为什么不将值存储到NSDictionary中?

时间:2021-06-10 23:56:11

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.

请参阅代码片段末尾的日志语句注释... acceleration.x是一个小数,但是当我将它存储到dict时,它似乎为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"]);

1 个解决方案

#1


When you call:

你打电话的时候:

[entry objectForKey: @"x"]

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

您将返回NSNumber实例而不是double值。将该行更改为:

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.

您将无法直接从NSDictionary检索double,因为键和值只能是对象,而不是基本类型。

#1


When you call:

你打电话的时候:

[entry objectForKey: @"x"]

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

您将返回NSNumber实例而不是double值。将该行更改为:

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.

您将无法直接从NSDictionary检索double,因为键和值只能是对象,而不是基本类型。