如何使用变量作为名称来创建和引用对象?
示例 -
for (int i=1; i<7; i++) {
CGRect ("myRectNum & i") = myImageView.bounds;
}
("myRectNum & 5").height etc ..
Run Code Online (Sandbox Code Playgroud) 如何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;
}
Run Code Online (Sandbox Code Playgroud) 我想在for循环中使用一些动态变量名,并且难以理解如何实际引用变量.
我有一系列UILabels冠军poll0- poll8.使用for循环,我将它们的text值设置为从数组中相应数字引用的另一个值.例如:
for (int i = 0; i < [pollData count]; i++) {
label(i value).text = [NSString stringWithFormat:@"%@", [[pollData objectAtIndex:i] toString]]; //sorry for the java-esque method names, just create what I'm used to
}
Run Code Online (Sandbox Code Playgroud)
我该如何使用该i值?
for-loop objective-c naming-conventions dynamic-variables ios
我一直在环顾四周,并没有找到任何关于这样做的事情,我不确定它是否可能,但这就是我想要实现的目标.请注意,我给出了一个非常简单的例子,说明我正在尝试做什么.此外,发布的代码的相似性都是假设的,并不意味着纠正代码语法.它仅用于通过引用类似的类型功能来帮助进一步说明所需的最终结果.所以在提供替代方法之前请先理解这个概念......
用那个说,正如标题所说,我试图看看我是否可以访问一个对象,让我们通过它的字符串名称或变量来说uilabel 而不使用if语句.例如,假设我们有3个uilabes
UILabel *label1;
UILabel *label2;
UILabel *label3;
Run Code Online (Sandbox Code Playgroud)
从那里我们做了所有适当的合成,什么不是.现在在某些时候我想引用一个基于let say和int的标签.
int intNumber = 2;
Run Code Online (Sandbox Code Playgroud)
这是理论部分.我现在想设置一个标签的文本,该标签的名称中包含匹配的int值.
label(%i, intNumber).text = [NSString stringWithFormat:@"This is Label %i", intValue];
Run Code Online (Sandbox Code Playgroud)
结果将是......
label2.text = @"This is Label 2";
Run Code Online (Sandbox Code Playgroud)
如果int值为1,则将更改label1.或者如果它是3,那么label3会被改变,等等......
或者如果使用标签的字符串名称可以完成相同的过程.
int intValue = 1;
NSString *labelName;
Run Code Online (Sandbox Code Playgroud)
然后在某个时候
labelName = [NSString stringWithFormat:@"label%i",intValue];
Run Code Online (Sandbox Code Playgroud)
现在以某种方式通过引用"labelName"来设置label1的文本来调用它.如果有人能提出建议或评论,甚至可以做到这样的事情,我将不胜感激.我知道你可以通过字符串名称引用类和选择器,但我不确定对象?我不知道"valueForKey:"是否应该是我应该这样做的方式?
对不起啰嗦的帖子感到抱歉,但我只是想确定我说出了我想做的事情.