初始化具有不同名称的多个对象 [英] Initialize multiple objects with different name

查看:51
本文介绍了初始化具有不同名称的多个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何Initializeallocate多个具有不同名称的对象并将其传递给NSArray.从下面的代码中,该对象被循环初始化一次,我需要多次初始化,因为For循环将使用不同的名称..然后将其传递给NSArray.请检查下面的代码. 当 For 循环将开始时,表示 i = 0 ..初始化项为tempItemi 现在下一次当 i = 1和i = 2 时,tempItemi名称将是相同的.我如何使用in循环更改此名称并将其传递给NSArray *items

How can I Initialize and allocate multiple objects with different name and pass it to the NSArray. from Below code the object is initialized once in loop and I need to initialized multiple times as per the For loop will go with different name..and then pass it to NSArray.please check the code below.. when For loop will start means i=0 ..initialized item would betempItemi now next time when i=1 and i=2 the tempItemi name will be same .how can i change this with in loop..and pass it to NSArray *items

for (int i = 0; i< [Array count]; i++)
{
    id object = [Array objectAtIndex:i];

    if ([object isKindOfClass:[NSDictionary class]])
    {
        NSDictionary *objDict = (NSDictionary *)object;


        ECGraphItem *tempItemi = [[ECGraphItem alloc]init];

        NSString *str = [objDict objectForKey:@"title"];

        NSLog(@"str value%@",str);
        float f=[str floatValue];
        tempItemi.isPercentage=YES;
        tempItemi.yValue=f;
        tempItemi.width=30;

        NSArray *items = [[NSArray alloc] initWithObjects:tempItemi,nil];
        //in array need to pass all the initialized values


        [graph drawHistogramWithItems:items lineWidth:2 color:[UIColor blackColor]];
    }
}

推荐答案

为什么不只是使数组可变,然后每次都添加对象,就像这样:

Why dont you just make the array mutable and then add the object each time like this:

NSMutableArray *items = [[NSMutableArray alloc] init];
// a mutable array means you can add objects to it!

for (int i = 0; i< [Array count]; i++)
{
    id object = [Array objectAtIndex:i];

    if ([object isKindOfClass:[NSDictionary class]])
    {
        NSDictionary *objDict = (NSDictionary *)object;


        ECGraphItem *tempItemi = [[ECGraphItem alloc]init];

        NSString *str = [objDict objectForKey:@"title"];

        NSLog(@"str value%@",str);
        float f=[str floatValue];
        tempItemi.isPercentage=YES;
        tempItemi.yValue=f;
        tempItemi.width=30;

        [items addObject: tempItemi];
        //in array need to pass all the initialized values

       }
}

    [graph drawHistogramWithItems:items lineWidth:2 color:[UIColor blackColor]];

无论如何,原始代码中的items每次都会重新初始化,并且每次都绘制一个新的直方图,因此您的代码将无法工作...这应该可以工作...

Anyways items in your original code will be reinitializing each time and you are drawing a new histogram each time so your code won't work... This should work...

这篇关于初始化具有不同名称的多个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆