Using a String representing the name of a variable to set the variable
This is a basic example that I know can be simplified, but for testing sake, I would like to do this in such a way. I want to set a variable based on an appending string (the variables "cam0" and "pos1" are already declared in the class). The appending string would essentially be an index, and i would iterate through a loop to assign cameras (cam0, cam1..) to different positions (pos0, pos1..).
cam0 is defined as an UIImageView
pos1 is defined as a CGRectThis works for a NSString Variable named coverIndex:
NSString* text = [[开发者_开发百科NSString alloc] initWithString:@""];
NSLog(@"%@",(NSString *)[self performSelector:NSSelectorFromString([text stringByAppendingString:@"coverIndex"])]);
The correct string that I set for coverIndex was logged to the Console.
Now back to my UIImageView and CGRect. I want this to work.
NSString* camText = [[NSString alloc] initWithString:@"cam"];
NSString* posText = [[NSString alloc] initWithString:@"pos"];
[(UIImageView *)[self performSelector:NSSelectorFromString([camText stringByAppendingString:@"0"])] setFrame:(CGRect)[self performSelector:NSSelectorFromString([posText stringByAppendingString:@"1"])]];
My error is "Conversion to non-scalar type requested"
This is the only way I found to do this sort of thing (and get the NSLog to work), but I still believe there is an easier way.
Thank you so much for any help :)
Use KVC, it's an amazing piece of technology that will do just what you want:
for (int index = 0; index < LIMIT; index++) {
NSString *posName = [NSString stringWithFormat:@"pos%d", index];
CGRect pos = [[self valueForKey:posName] CGRectValue];
NSString *camName = [NSString stringWithFormat:@"cam%d", index];
UIImageView *cam = [self valueForKey:camName];
cam.frame = pos;
}
One way you can do this would be to create your cameras in a dictionary and use those special NSStrings to key in to it. Like,
NSMutableDictionary *myCams;
myCams = [[myCams alloc] init];
[myCams addObject:YOUR_CAM0_OBJECT_HERE forKey:@"cam[0]"];
[myCams addObject:YOUR_CAM1_OBJECT_HERE forKey:@"cam[1]"];
NSString camString = @"cam[0]"; // you'd build your string here like you do now
id theCamYouWant = [myCams objectForKey:camString];
精彩评论