首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将缺少的年份和相应的值添加到数组中

将缺少的年份和相应的值添加到数组中
EN

Stack Overflow用户
提问于 2015-04-26 02:06:46
回答 1查看 25关注 0票数 0

我一直在摆弄JBChartView库,它看起来非常适合用来绘制图表。它很容易使用,但我在获取特定图表所需格式的数据时遇到了一些问题。

用户可以输入值和相应的年份。这是使用核心数据保存的。数据可能如下所示:

年份:0值: 100年:2值200年3值150

我将创建两个数组,一个用于年份编号,另一个用于值。不过在这种情况下,我会得到3个条形。我想要的是一年的值为0的条形图。

我认为最好的方法是查看Year数组,检查第一个值是否为0,然后检查每连续一年的值是否为+1。如果不是,则将1加到前一年,并在values数组的相同索引位置插入一个值0。

我想知道这是不是最好的方法,以及我是否可以得到一些帮助来进行比较。

谢谢

EN

回答 1

Stack Overflow用户

发布于 2015-04-27 02:39:19

好了,我找到了我自己的问题的答案,我想我应该把它贴出来,因为它可能会对将来的人有所帮助,特别是在使用这个或其他库创建图表时。

我首先填充2个可变数组

代码语言:javascript
复制
chartLegend = [NSMutableArray arrayWithObjects:@1,@3, nil];
chartData = [NSMutableArray arrayWithObjects:@"100",@"300", nil];

因此我得到了年份1和年份3,每个年份在chartData数组中都有一个关联值。

我现在需要创建一个年份0和年份2,以便我的条形图在从0到我的最大年份3的每一年都有一个条形图。

代码语言:javascript
复制
- (void)addItemsToArray {

for (int i=0; i<[chartLegend count]; i++)
{


    //get the values from our array that are required for any calculations
    int intPreviousValue = 0;
    int intCurrentValue = [[chartLegend objectAtIndex:i]integerValue];

    if (i>0)
    {
        intPreviousValue = [[chartLegend objectAtIndex:(i-1)]integerValue];
    }



    //Deal with the first item in the array which should be 0
    if (i == 0)
    {
        if (intCurrentValue != 0)
        {
            [chartLegend insertObject:[NSNumber numberWithInt:0] atIndex:i];
            [chartData insertObject:[NSNumber numberWithInt:0] atIndex:i];
        }

    }

    //Now deal with all other array items
    else if (intCurrentValue - intPreviousValue !=1)
    {
        int intNewValue = intPreviousValue +1;

        [chartLegend insertObject:[NSNumber numberWithInt:intNewValue] atIndex:i];
        [chartData insertObject:[NSNumber numberWithInt:0] atIndex:i];
    }




}


//create a string with all of the values in the array
NSString *dates = [chartLegend componentsJoinedByString:@","];
NSString *values = [chartData componentsJoinedByString:@","];

//display the text in a couple of labels to check you get the intended result
self.yearsLabel.text = dates;
self.valuesLabel.text = values;

}

这似乎对我很有效。使用coreData信息填充数组应该很容易,只需确保它首先排序即可。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29868820

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档