基于 int 创建多个编号变量
如何使用数组的计数创建多个 NSDictionary 变量?
这基本上是我想到的,但我不确定如何使用 Objective-C 语法来实现它。 doesntContainAnother
是一个 NSArray
。我希望字典的名称使用 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;
}
How would I create a number of NSDictionary
variables using an array's count?
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
创建一个可变数组并循环,直到达到原始数组的计数,创建一个字典并在每次迭代时将其添加到可变数组中。
您的代码应该如下所示。
创建名称末尾带有数字的变量的方法是一种反模式,在 Objective-C 中甚至是不可能的。它相当于一个数组,但更笨重。
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.
Your code should look like this.
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.
您需要创建一个可变数组,然后将对象放入该数组中。您不能像您所做的那样创建与字符串内容同名的变量。例如:
或者如果您想按名称将它们从列表中取出:
但第一种方法可能是最简单的。
You need to create a mutable array, and then put the objects into the array. You can't create a variable with the same name as the contents of a string, as you have done. For example:
Or if you want to pull them out of the list by name:
But the first way is likely the easiest.