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

后端 未结 2 455
傲寒
傲寒 2021-01-03 12:41

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 (th

相关标签:
2条回答
  • 2021-01-03 13:03

    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;
    }
    
    0 讨论(0)
  • 2021-01-03 13:06

    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];
    
    0 讨论(0)
提交回复
热议问题