Using a String representing the name of a variable to set the variable

陌路散爱 提交于 2020-01-29 05:44:09

问题


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 CGRect

This 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 :)


回答1:


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;
}



回答2:


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];


来源:https://stackoverflow.com/questions/5680284/using-a-string-representing-the-name-of-a-variable-to-set-the-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!