Calling properties/instance variables from strings in Objective-C
Basically my view controller has 49 different instance variables of class CircleView
(called circleView1
, circleView2
, ..., circleView49
). The CircleView
class is a simple subclass of UIImageView
and basically returns a circle picture when initialized.
Here is what I am trying to do:
In my implementation for the view controller, I want to be able to select the instance variable using a string, for example let's say I generate a random integer i
between 1 and 49, lets say it's 5. I would like to be able to build an NSString using something like [NSString stringWithFormat @"circleView%i",i];
and somehow reach the actual circleView5 instance variable. Is this possible?
P.S. I'm looking for something in the lines of NSClassFromString
, but which applies to instance variables or objects.
KVC is your friend. Assuming you have a string with the name of the circleView in it,
NSString *myCircle = [NSString stringWithFormat:@"circleView%i", i];
you access that property on the controller using KVC:
CircleView *theCircle = [self valueForKey:myCircle];
On a side note, you should consider redesigning the object heirarchary; this will be very difficult to maintain, and there are certainly better ways to do it (an array with the CircleView's accessed by index would be my first choice).
Instead of having a pile of variables and trying to access them via a string, use an array (either a primitive C array or an NSArray: I'll demo with an NSMutableArray). Declare a NSMutableArray *circleViews;
in your class like you did the circleViewN
instances. In your initializer, instead of a bunch of circleViewN = [[CircleView alloc] init];
, you'd have something like:
circleViews = [NSMutableArray arrayWithCapacity:50];
for(int i=0; i<50; i++)
[circleViews addObject:[[[CircleView alloc] init] autorelease]];
Then you can access the desired circle with your random int i
with [circleViews objectAtIndex:i];
.
精彩评论