santobedi
santobedi

Reputation: 858

How to store and retrieve NSArray as value and float as key in/from NSDictionary?

A NSDictionary in my code contains NSArrays with their respective keys (keys are float variables). When I tried to retrieve the NSArray using their respective keys, I get null value. I tried using both ObjectForKey and valueForKey methods, however the result is null. 'DictOfCoordinatesWrtDist' is a NSDictionary which contains 2-D coordinates(NSArray) as value and distance (NSNumber floatValue) as their respective keys. I want to retrieve those coordinates with their keys later in the code. While using objectForKey and valueForKey methods, the coordinates are null.

NSArray *AllDistsWrtBeacons = [DictOfCoordinatesWrtDist allKeys];
for( id dist in AllDistsWrtBeacons)
{ NSArray *beaconCoordinate = [DictOfCoordinatesWrtDist objectForKey:dist];


NSLog(@"X=%@ Y=%@", [beaconCoordinate objectAtIndex:0],[beaconCoordinate objectAtIndex:1]);}

P.S: The NSDictionary 'DictOfCoordinatesWrtDist' contains beacons coordinate (Value) with respect to their distance (key). After executing this code, I get null value as coordinate.

Upvotes: 0

Views: 799

Answers (4)

MrWaqasAhmed
MrWaqasAhmed

Reputation: 1489

 [dict setObject:myArray forKey:[NSNumber numberWithFloat:1.0]];

Upvotes: 1

iSashok
iSashok

Reputation: 2446

You need convert your keys float to NSNumber or NSString like that:

NSDictionary *dict = @{
   @(YOUR float Value) : @[Your array]
};

And I think more readable declare it using literals

Upvotes: 0

Ekta Padaliya
Ekta Padaliya

Reputation: 5799

You can use below code.

NSArray *temp = @[@"1",@"2"];
NSDictionary *dic = @{
                            [NSNumber numberWithFloat:1.0] : temp,
                            @"Test1" : [NSNumber numberWithInt:22]
                            };
NSLog(@"Get dic with number = %@",[dic objectForKey:[NSNumber numberWithFloat:1.0]]);

Upvotes: 1

Ketan Parmar
Ketan Parmar

Reputation: 27438

You can't use direct float or integer, As NSDictionarys are only designed to deal with objects, a simple way to do this is to wrap the integer and float in a NSNumber object.

For example,

NSArray *arr1 = [[NSArray alloc]initWithObjects:@"one",@"two", nil];
NSArray *arr2 = [[NSArray alloc]initWithObjects:@"red",@"green", nil];

NSNumber *key1 = [NSNumber numberWithFloat:1.1];
NSNumber *key2 = [NSNumber numberWithFloat:2.1];

NSDictionary *dict = [[NSDictionary alloc]initWithObjectsAndKeys:arr1,key1,arr2,key2, nil];

NSLog(@"%@",[dict objectForKey:key1]);

NSLog(@"%@",[dict objectForKey:key2]);

Upvotes: 1

Related Questions