开发者

Convert a string + a number to an onject

I am new to Obj C, but familiar with OOP. I am working on a game that uses collision detection to score points and change UIImageView properties like background color.

I have a finite number of UIImageViews that are subviews of a larger view. I can manually check for collision and set the background colors of the UIImageViews accordingly. The problem is that this creates a rather large if / else block that I can see growing out of control. In JavaScript I can use a for loop and eval() to evaluate a string + i (the loop var) and then simply call the new var.backgroundColor = someColor;

It seems that eval is not used in OBJ C, so I am looking for an equivalent that will allow开发者_StackOverflow me to create a loop that executes the same block of code on a given object that only differs from other objects by name only:

Example:

if (someStatement == true){ object_01.someProperty = newProperty; } else if (someOtherStatement == true){ object_02.someProperty = newProperty; } else if (someOtherOtherStatement == true){ object_03.someProperty = newProperty; }

I want to write the above as a loop. I realize I can use an Array, but if so, how? Also, I want to loop through CGRects which are not storing properly in an Array.

Any help greatly appreciated!

Damon


Creating your array:

NSMutableArray *items = [NSMutableArray array];

Populating your array with CGRects:

[items addObject:[NSValue valueWithCGRect:frame]];

Pulling a CGRect from the array:

CGRect frame = [[items objectAtIndex:0] CGRectValue];

Replacing an index in the array:

[items replaceObjectAtIndex:0 withObject:[NSValue valueWithCGRect:frame]];


The best way is to put object_01, object_02, ... into an array and then use `-[NSArray objectAtIndex:] to access the objects.

You could also use Key-Value Coding:

NSString *keyPath = [NSString stringWithFormat:@"object_0%d.someProperty", objectIndex];
[self setValue:newProperty forKeyPath:keyPath];

But as rpetrich mentioned, it's not good programming style.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜