This might be a completely ridiculous question, but is it possible to use a NSString as a substitute for a line of code?
for (int i = 0; i < 10: i++){
NSString *cam = @"locXCamProfileSwitch";
["%@", cam setOn:YES];
]
Also is it possible to concantinate the index i into the replacement of the X?
It's not generally possible (as far as I know), but it's possible to access ivars, properties, classes and methods by using strings.
Instance variables and properties can be accessed like this:
[self valueForKey:@"key"];
Classes can be referenced like this:
Class cls = NSClassFromString(@"MyClass");
[cls aClassMethod];
Methods can be used like this:
SEL selector = NSSelectorFromString(@"myMethod:");
[self performSelector:selector];
To replace a placeholder in a string with a number you can use a formatter:
NSString *cam = [NSString stringWithFormat:@"loc%dCamProfileSwitch", i];
That being said, it's never a good idea to have numbered variable names.
Use an array instead:
int switchCount = 10;
NSMutableArray *switches = [[NSMutableArray alloc] initWithCapacity:switchCount];
for (int i = 0; i < switchCount; i++) {
CGRect rect = CGRectMake(10, 10+i*30, 70, 40); // or something like that.
UISwitch *sw = [[UISwitch alloc] initWithFrame:rect];
sw.tag = i;
[sw addTarget:self action:@selector(switchChanged:)
forControlEvents:UIControlEventValueChanged];
[self.view addSubview:sw];
[switches addObject:sw];
}
self.switches = [NSArray arrayWithArray:switches]; // assuming you have a property "switches".
Then you can simply iterate over it:
for (UISwitch *switch in self.switches) {
[switch setOn:YES];
}
And be notified when one of them changes like this:
- (void)switchChanged:(id)sender {
UISwitch *theSwitch = (UISwitch *)sender; // the switch that changed.
int tag = theSwitch.tag; // number of switch that changed.
// do something....
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With