Andrew Johnson
Andrew Johnson

Reputation: 13286

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],
  nil];
NSLog([NSString stringWithFormat:@"%@", [NSNumber numberWithDouble:acceleration.x]]);
NSLog([NSString stringWithFormat:@"%@", [entry objectForKey:@"x"]]);

Upvotes: 38

Views: 66968

Answers (3)

Nemo
Nemo

Reputation: 588

new Objective-c supports this new syntax for static initialisation.

@{key:value}

For example:

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

Upvotes: 23

satzkmr
satzkmr

Reputation: 87

NSDictionary Syntax:

NSDictionary *dictionaryName = [NSDictionary dictionaryWithObjectsAndKeys:@"value1",@"key1",@value2",@"key2", nil];

Example:

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

Output looking like,

{India = NewDelhi; Japan = Tokyo; UnitedKingdom = London; }

Upvotes: 6

Massimo Cafaro
Massimo Cafaro

Reputation: 25429

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];

Upvotes: 107

Related Questions