使用不同的名称初始化多个对象

我怎样才能Initializeallocate多个不同名称的对象,并将其传递给NSArray 。 从下面的代码对象初始化一次循环,我需要多次初始化为每个For循环将不同的名称..然后传递给NSArray请检查下面的代码..当循环将开始意味着我= 0 ..初始化的项目将tempItemi现在下一次当我= 1和我= 2tempItemi名称将是相同的。我可以改变这与循环..并将其传递给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]]; } } 

为什么不让数组可变,然后每次像这样添加对象:

 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将重新初始化每次,你是每次绘制一个新的直方图,所以你的代码将无法正常工作…这应该工作…

你写的代码是好的,但是NSArray *items在每个循环中总是只包含一个项目。 只需将外部for循环声明为NSMutableArray ,并使用您正在使用的相同代码。

正如你所说的你想要dynamicvariables

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

在这里, i将在循环中改变,

您可以创build一个NSDictionary键/值与您的tempItem1 / 2/3/4 ….作为关键,并通过alloc / init保存值。

然后,而不是一个variablestempItem32 ,你将使用[dict valueForKey:@"tempItem32"]

编辑:

检查这个例子,如果这可能会得心应手

 NSMutableDictionary *dict=[NSMutableDictionary new]; for (int i=1; i<11; i++) { NSString *string=[NSString stringWithFormat:@"string%d",i]; [dict setObject:[NSString stringWithFormat:@"%d", i*i] forKey:string]; } NSLog(@"dict is %@",dict); NSString *fetch=@"string5"; NSLog(@"val:%@, for:%@",[dict valueForKey:fetch],fetch);