Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"]]);
like image 445
Andrew Johnson Avatar asked Jul 10 '09 06:07

Andrew Johnson


People also ask

How do I create an NSDictionary in Objective-C?

Creating NSDictionary Objects Using Dictionary Literals In addition to the provided initializers, such as init(objects:forKeys:) , you can create an NSDictionary object using a dictionary literal. In Objective-C, the compiler generates code that makes an underlying call to the init(objects:forKeys:count:) method.

Does NSDictionary retain objects?

An NSDictionary will retain it's objects, and copy it's keys.

How do I know if NSDictionary is empty?

if (myDict. count) NSLog(@"Dictionary is not empty"); else NSLog(@"Dictionary is empty"); Every number that is 0 equals to @NO . Every number that is not 0 equals to @YES .


3 Answers

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];
like image 199
Massimo Cafaro Avatar answered Sep 22 '22 20:09

Massimo Cafaro


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]};
like image 39
Nemo Avatar answered Sep 25 '22 20:09

Nemo


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

like image 22
satzkmr Avatar answered Sep 22 '22 20:09

satzkmr