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

心已入冬 提交于 2019-11-30 16:24:26

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