Evaulate NSString并作为Objective-C代码执行

Tas*_*que 3 loops concatenation objective-c nsstring

这可能是一个完全荒谬的问题,但是有可能使用a NSString作为代码行的替代品吗?

for (int i = 0; i < 10: i++){    
    NSString *cam = @"locXCamProfileSwitch";
    ["%@", cam setOn:YES];
]
Run Code Online (Sandbox Code Playgroud)

也有可能将索引i汇入更换X

Dru*_*erB 5

通常不可能(据我所知),但是可以通过使用字符串来访问ivars,属性,类和方法.

要使用数字替换字符串中的占位符,可以使用格式化程序:

NSString *cam = [NSString stringWithFormat:@"loc%dCamProfileSwitch", i];
Run Code Online (Sandbox Code Playgroud)

话虽如此,拥有编号的变量名称绝不是一个好主意.

改为使用数组:

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".
Run Code Online (Sandbox Code Playgroud)

然后你可以简单地迭代它:

for (UISwitch *switch in self.switches) {
    [switch setOn:YES];
}
Run Code Online (Sandbox Code Playgroud)

当其中一个改变时会收到通知:

- (void)switchChanged:(id)sender {
    UISwitch *theSwitch = (UISwitch *)sender; // the switch that changed.
    int tag = theSwitch.tag;  // number of switch that changed.
    // do something....
}
Run Code Online (Sandbox Code Playgroud)