基于 int 创建多个编号变量 [英] Create multiple numbered variables based on a int
问题描述
如何使用数组的计数创建多个 NSDictionary
变量?
How would I create a number of NSDictionary
variables using an array's count?
这基本上是我想出的,但我不确定如何使用 Objective-C 语法使其工作.doesntContainAnother
是一个 NSArray
.我希望字典的名称使用 loopInt
的当前值.
This is basically what I came up with, but I'm not sure how to make this work with Objective-C syntax. doesntContainAnother
is an NSArray
. I want the names of the dictionaries to use the current value of loopInt
.
int *loopInt = 0;
while (doesntContainAnother.count <= loopInt) {
NSMutableDictionary *[NSString stringWithFormat:@"loopDictionary%i", loopInt] = [[[NSMutableDictionary alloc] init] autorelease];
[NSString stringWithFormat:@"loopDictionary%i", loopInt] = [NSDictionary dictionaryWithObject:[array1 objectAtIndex:loopInt]
forKey:[array2 objectAtIndex:loopInt]];
loopInt = loopInt + 1;
}
推荐答案
创建一个可变数组并循环直到达到原始数组的计数,创建一个字典并在每次迭代时将其添加到可变数组中.
Create a mutable array and loop until you reach the original array's count, creating a dictionary and adding it to the mutable array on each iteration.
您的代码应如下所示.
NSMutableArray *dictionaries = [[NSMutableArray alloc] init];
for (int i = 0; i < doesntContainAnother.count; i++) {
[dictionaries addObject:[NSMutableDictionary dictionaryWithObject:[array1 objectAtIndex:i] forKey:[array2 objectAtIndex:i]]];
}
创建变量名末尾带有数字的方法是一种反模式,甚至在 Objective-C 中是不可能的.它相当于一个数组,但更笨重.
The approach of creating variables with numbers at the end of their names is an antipattern and not even possible in Objective-C. It's equivalent to an array, but clunkier.
这篇关于基于 int 创建多个编号变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!