views:

200

answers:

1

I'm iterating through some objects and trying to set some properties that, apparently, don't like Key-Value coding. so I'm unable to create a string at runtime to represent the "key".

This line of ViewController won't compile:

[self setValue:offsetX forKeyPath:[NSString stringWithFormat:@"myView%d.center.x", anInt]];

but I can set these properties with dot notation in a ridiculous switch statement:

myView1.center.x = offsetX;

Is there another way to go about this? perhaps create an accessor like myView(i).center.x ? Knowing full well it was going to be futile, i even tried: [NSString stringWithFormat:@"myView%d", anInt].center.x
to no avail...

+3  A: 

The reason it wont compile is presumably because offsetX is an int or float, not an NSNumber (it would be helpful to give the compiler error message in your question).

However KVC and setValue:forKeyPath: is very clever and will automatically convert from an NSNumber for you, so use:

[self setValue:[NSNumber numberWithInt:offsetX] forKeyPath:[NSString stringWithFormat:@"myView%d.center.x", anInt]];

(or numberWithFloat as appropriate).

Peter N Lewis
That works brilliantly! Thanks! And your approach led me to figure out my next question which was setting myViewX.center which is a CGPoint in a similar way by setting the value to [NSValue valueWithCGPoint:centerPoint] instead of just centerPoint...lifesaver!
Meltemi
Hmmmm. Now stuck on how to wrap a bool for use in KVC in something like this:[self setValue:YES forKeyPath:[NSString stringWithFormat:@"@myView%d.userInteractionEnabled"]];
Meltemi
BOOLs can be wrapped in NSNumber's.
Peter N Lewis