我是Obj C的新手,但熟悉OOP。我正在开发一款游戏,它使用碰撞检测来获得积分并更改UIImageView属性,例如背景颜色。
我有一定数量的UIImageViews是更大视图的子视图。我可以手动检查碰撞并相应地设置UIImageViews的背景颜色。问题是,这会产生一个相当大的if / else块,我可以看到它越来越失控。在JavaScript中,我可以使用for循环和eval()来计算字符串+ i(循环变量),然后简单地调用新的var.backgroundColor = someColor;
似乎eval没有在OBJ C中使用,所以我正在寻找一个等价物,它允许我创建一个循环,在给定的对象上执行相同的代码块,只与名称的其他对象不同:
示例:
if(someStatement == true){ object_01.someProperty = newProperty; } else if(someOtherStatement == true){ object_02.someProperty = newProperty; } else if(someOtherOtherStatement == true){ object_03.someProperty = newProperty; }
我想把上面的内容写成循环。我意识到我可以使用数组,但如果是这样,怎么样?另外,我想循环遍历没有正确存储在数组中的CGRect。
任何帮助都非常感谢!
戴蒙
答案 0 :(得分:0)
创建阵列:
NSMutableArray *items = [NSMutableArray array];
使用CGRect
s:
[items addObject:[NSValue valueWithCGRect:frame]];
从数组中提取CGRect
:
CGRect frame = [[items objectAtIndex:0] CGRectValue];
替换数组中的索引:
[items replaceObjectAtIndex:0 withObject:[NSValue valueWithCGRect:frame]];
答案 1 :(得分:0)
最好的方法是将object_01
,object_02
,...放入数组中,然后使用` - [NSArray objectAtIndex:]来访问对象。
您也可以使用Key-Value Coding:
NSString *keyPath = [NSString stringWithFormat:@"object_0%d.someProperty", objectIndex];
[self setValue:newProperty forKeyPath:keyPath];
但正如rpetrich所说,这不是很好的编程风格。