如何形成一个if语句来选择几个词典中的一个?

时间:2014-07-30 03:04:54

标签: ios objective-c if-statement dictionary

我需要将键值插入等式中。这些值需要来自一个字典或另一个字典,基于分段控件的位置。

以下是分段控件的代码:

- (IBAction)tankChooser:(UISegmentedControl *)sender
{
    if (_tankControl.selectedSegmentIndex ==0)
    {
        bigTank = YES;
        tankType = @"dragon500";
    }
    if (_tankControl.selectedSegmentIndex ==1)
    {
        bigTank = NO;
        tankType = @"skid250";
    }
    if (_tankControl.selectedSegmentIndex ==1)
    {
        bigTank = YES;
        tankType = @"hyTech500";
    }
}

这是我一直用于使用单字典的方法,它完美无缺。

- (void)calculateRate
    {
    NSString *dragonPath = [[NSBundle mainBundle] pathForResource:@"dragonBarrelChart" ofType:@"plist"];
    NSDictionary *dragonBarrelChart = [NSDictionary dictionaryWithContentsOfFile: dragonPath];

NSString *startKey = [NSString stringWithFormat:@"%@%@", self.startLevel.text, startFractions];

    NSString *startValue = dragonBarrelChart[startKey];

本质上,我需要一种方法来实现它,以便当用户在分段控件上选择一个按钮时,它会导致NSString * startvalue从不同的字典中获取其键/值,如下所示:

    NSString *hyTechPath = [[NSBundle mainBundle] pathForResource:@"hyTechBarrelChart" ofType:@"plist"];
NSDictionary *hyTechBarrelChart = [NSDictionary dictionaryWithContentsOfFile: hyTechPath];

如果我可以提供更多信息,请告知。在此先感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

如果我理解正确,你的目标是检索" Chart"来自plist文件的数据,其对应于用户选择的罐的类型。一种方法是将资源的名称保存在一个实例变量中,calculateRate随后会用它来检索正确的字典。你的tankChooser方法看起来像这样。

- (IBAction)tankChooser:(UISegmentedControl *)sender
{
    if (_tankControl.selectedSegmentIndex ==0)
    {
        bigTank = YES;
        tankType = @"dragon500";
        tankResource = @"dragonBarrelChart";
    }
    if (_tankControl.selectedSegmentIndex ==1)
    {
        bigTank = NO;
        tankType = @"skid250";
        tankResource = @"skidBarrelChart";
    }
    if (_tankControl.selectedSegmentIndex ==2)//assuming you meant 2 here
    {
        bigTank = YES;
        tankType = @"hyTech500";
        tankResource = @"skidBarrelChart";
    }
}

然后在费率计算器方法中:

- (void)calculateRate
{
    NSString *tankPath = [[NSBundle mainBundle] pathForResource:tankResource ofType:@"plist"];
    NSDictionary *tankBarrelChart = [NSDictionary dictionaryWithContentsOfFile: tankPath];
    //and then use this to get startValue.
}