Sumit singh
Sumit singh

Reputation: 2446

How We store Float value in NSMutableDictionary

- (void)buttonSave:(UIButton *)bttnSave
{
    UILabel *lbl = (UILabel *)[self.view viewWithTag:kTagLblText];
    [dicStore setValue:lbl.textColor forKey:@"Text Color"];

    // fltValue is float type 
    [dicStore setObject:fltValue forKey:@"font"];

    [dicStore setValue:strtextView forKey:@"Text Style"];
    [arrStoreDic addObject:dicStore];
}

If We can store this then any one can help me please do

Upvotes: 1

Views: 5497

Answers (4)

lsaudon
lsaudon

Reputation: 1468

NSDictionary *dict = @{@"floatProperty":[NSNumber numberWithFloat:floatValue]};

Upvotes: 0

trojanfoe
trojanfoe

Reputation: 122449

Simply:

dicStore[@"font"] = @(fltValue);

However it's troubling that dicStore is an instance variable that you want to store into an array, which leads me to believe you will end up with an array of the same dictionary, containing the same values.

Instead create a new dictionary each time and store it into the array (unless, of course, other code needs to see this dictionary). The current implementation is very brittle.

Upvotes: 11

Michaël Azevedo
Michaël Azevedo

Reputation: 3896

NSMutableDictionary, NSarray, NSSet and other collection classes accept only objects, and a float variable is a primitive. You have to create a NSNumber object from your float :

NSNumber * floatObject =[NSNumber numberWithFloat:fltValue]
[dicStore setObject:floatObject forKey:@"font"];

Using literals, your code can be simplified to :

 -(void)buttonSave:(UIButton *)bttnSave
{
    UILabel *lbl = (UILabel *)[self.view viewWithTag:kTagLblText];

    dicStore[@"Text Color"] = lbl.textColor;
    dicStore[@"font"] = @(fltValue);
    dicStore[@"Text Style"] = strtextView;

    [arrStoreDic addObject:dicStore];
}

To get back the float value, it's pretty simple :

NSNumber * floatNumber = dicStore[@"font"];
float floatValue = floatNumber.floatValue;

Upvotes: 1

Suresh Thoutam
Suresh Thoutam

Reputation: 258

NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:
                       [NSArray arrayWithObjects:[NSNumber numberWithFloat:0.5], [NSNumber numberWithFloat:0.7], [NSNumber numberWithFloat:0.2], nil],
                       nil];

The above code is used to add float values in Dictionary 

Upvotes: 3

Related Questions