我们如何在NSMutableDictionary中存储Float值

时间:2014-11-06 10:57:12

标签: ios 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];
}

如果我们可以存储这个,那么任何人都可以帮助我做

4 个答案:

答案 0 :(得分:7)

简单地:

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

然而令人不安的是dicStore是一个你想要存储到数组中的实例变量,这让我相信你最终会得到一个包含相同值的同一个字典的数组。

每次都创建一个新的字典并将其存储到数组中(当然,除非其他代码需要查看这个字典)。目前的实施非常脆弱。

答案 1 :(得分:3)

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 

答案 2 :(得分:1)

NSMutableDictionaryNSarrayNSSet和其他集合类只接受对象,而float变量是基元。你必须从你的浮动创建一个NSNumber对象:

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

使用文字,您的代码可以简化为:

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

要获取浮动值,它非常简单:

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

答案 3 :(得分:0)

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