这可能是一个完全荒谬的问题,但是否可以使用 NSString
代替一行代码?
for (int i = 0; i < 10: i++){
NSString *cam = @"locXCamProfileSwitch";
["%@", cam setOn:YES];
]
还有可能将索引 i
连接到 X
的替换中吗?
最佳答案
这通常是不可能的(据我所知),但可以使用字符串访问 ivar、属性、类和方法。
可以像这样访问实例变量和属性:
[self valueForKey:@"key"];
类可以这样引用:
Class cls = NSClassFromString(@"MyClass"); [cls aClassMethod];
方法可以这样使用:
SEL selector = NSSelectorFromString(@"myMethod:"); [self performSelector:selector];
要用数字替换字符串中的占位符,您可以使用格式化程序:
NSString *cam = [NSString stringWithFormat:@"loc%dCamProfileSwitch", i];
话虽如此,使用编号的变量名绝不是一个好主意。
改用数组:
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".
然后你可以简单地迭代它:
for (UISwitch *switch in self.switches) {
[switch setOn:YES];
}
并在其中一个发生这样的变化时得到通知:
- (void)switchChanged:(id)sender {
UISwitch *theSwitch = (UISwitch *)sender; // the switch that changed.
int tag = theSwitch.tag; // number of switch that changed.
// do something....
}
关于objective-c - 评估字符串并作为 Objective-C 代码执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12800988/