创建NSDictionary

And*_*son 33 iphone cocoa-touch

在以下代码中,第一个日志语句按预期显示小数,但第二个日志语句为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"]]);
Run Code Online (Sandbox Code Playgroud)

Mas*_*aro 104

您正在交换插入对象和键的顺序:您需要首先插入对象,然后插入密钥,如以下示例所示.

NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:@"value1", @"key1", @"value2", @"key2", nil];
Run Code Online (Sandbox Code Playgroud)

  • 如果您的值是动态放置的,请特别注意是否有任何值为空。这可能会使字典的创建在中间停止,因为“nil”是方法分派中的哨兵。如果需要,请进行验证。`NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:@"value1"?nil:@"", @"key1", @"value2"?nil:@"", @"key2", nil];` (2认同)

Nem*_*emo 21

新的Objective-c支持静态初始化的这种新语法.

@{key:value}
Run Code Online (Sandbox Code Playgroud)

例如:

NSDictionary* dict = @{@"x":@(acceleration.x), @"y":@(acceleration.y), @"z":@(acceleration.z), @"date":[NSDate date]};
Run Code Online (Sandbox Code Playgroud)


小智 6

NSDictionary语法:

NSDictionary *dictionaryName = [NSDictionary dictionaryWithObjectsAndKeys:@"value1",@"key1",@value2",@"key2", nil];
Run Code Online (Sandbox Code Playgroud)

例:

NSDictionary *importantCapitals = [NSDictionary dictionaryWithObjectsAndKeys:
@"NewDelhi",@"India",@"Tokyo",@"Japan",@"London",@"UnitedKingdom", nil];
NSLog(@"%@", importantCapitals);
Run Code Online (Sandbox Code Playgroud)

输出看起来像,

{India = NewDelhi; 日本=东京; UnitedKingdom =伦敦; }