在以下代码中,第一个日志语句按预期显示小数,但第二个日志语句为NULL。我做错了什么?
NSDictionary *entry = [[NSDictionary alloc] initWithObjectsAndKeys:
@"x", [NSNumber numberWithDouble:acceleration.x],
@"y", [NSNumber numberWithDouble:acceleration.y],
@"z", [NSNumber numberWithDouble:acceleration.z],
@"date", [NSDate date],
nil];
NSLog([NSString stringWithFormat:@"%@", [NSNumber numberWithDouble:acceleration.x]]);
NSLog([NSString stringWithFormat:@"%@", [entry objectForKey:@"x"]]);
答案 0 :(得分:104)
您正在交换插入对象和键的顺序:您需要首先插入对象,然后插入键,如下例所示。
NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:@"value1", @"key1", @"value2", @"key2", nil];
答案 1 :(得分:18)
新的Objective-c支持这种静态初始化的新语法。
@{key:value}
例如:
NSDictionary* dict = @{@"x":@(acceleration.x), @"y":@(acceleration.y), @"z":@(acceleration.z), @"date":[NSDate date]};
答案 2 :(得分:6)
NSDictionary语法:
NSDictionary *dictionaryName = [NSDictionary dictionaryWithObjectsAndKeys:@"value1",@"key1",@value2",@"key2", nil];
示例:强>
NSDictionary *importantCapitals = [NSDictionary dictionaryWithObjectsAndKeys:
@"NewDelhi",@"India",@"Tokyo",@"Japan",@"London",@"UnitedKingdom", nil];
NSLog(@"%@", importantCapitals);
输出看起来像,
{India = NewDelhi;日本=东京; UnitedKingdom =伦敦; }