计算NSString并作为Objective-C代码执行
这可能是一个完全荒谬的问题,但是否可以使用计算NSString并作为Objective-C代码执行,objective-c,loops,nsstring,concatenation,Objective C,Loops,Nsstring,Concatenation,这可能是一个完全荒谬的问题,但是否可以使用NSString替代一行代码 for (int i = 0; i < 10: i++){ NSString *cam = @"locXCamProfileSwitch"; ["%@", cam setOn:YES]; ] for(inti=0;i
NSString
替代一行代码
for (int i = 0; i < 10: i++){
NSString *cam = @"locXCamProfileSwitch";
["%@", cam setOn:YES];
]
for(inti=0;i<10:i++){
NSString*cam=@“locXCamProfileSwitch”;
[“%@”,凸轮设置:是];
]
还可以将索引
i
集中到X
的替换中吗?将所有开关添加到一个数组中,并使用其索引迭代该数组。通常不可能(据我所知),但可以使用字符串访问IVAR、属性、类和方法
- 实例变量和属性的访问方式如下:
[self valueForKey:@"key"];
Class cls = NSClassFromString(@"MyClass"); [cls aClassMethod];
SEL selector = NSSelectorFromString(@"myMethod:"); [self performSelector:selector];
- (void)switchChanged:(id)sender { UISwitch *theSwitch = (UISwitch *)sender; // the switch that changed. int tag = theSwitch.tag; // number of switch that changed. // do something.... }
- 类可以这样引用:
[self valueForKey:@"key"];
Class cls = NSClassFromString(@"MyClass"); [cls aClassMethod];
SEL selector = NSSelectorFromString(@"myMethod:"); [self performSelector:selector];
- (void)switchChanged:(id)sender { UISwitch *theSwitch = (UISwitch *)sender; // the switch that changed. int tag = theSwitch.tag; // number of switch that changed. // do something.... }
- 方法可以这样使用:
[self valueForKey:@"key"];
Class cls = NSClassFromString(@"MyClass"); [cls aClassMethod];
SEL selector = NSSelectorFromString(@"myMethod:"); [self performSelector:selector];
- (void)switchChanged:(id)sender { UISwitch *theSwitch = (UISwitch *)sender; // the switch that changed. int tag = theSwitch.tag; // number of switch that changed. // do something.... }
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".
并在其中一个发生如下更改时收到通知:
[self valueForKey:@"key"];
Class cls = NSClassFromString(@"MyClass");
[cls aClassMethod];
SEL selector = NSSelectorFromString(@"myMethod:");
[self performSelector:selector];
- (void)switchChanged:(id)sender {
UISwitch *theSwitch = (UISwitch *)sender; // the switch that changed.
int tag = theSwitch.tag; // number of switch that changed.
// do something....
}
看
但本质上你做错了。创建一个由10个开关组成的数组并对其进行迭代。不,但你可以使用字符串访问方法或属性-你到底想做什么?你想将10个开关设置为打开状态吗?这不是正确的方法。将它们全部添加到数组中并使用它。@Drummer这正是w我想做的是,你能给我举个例子吗?我怎样才能将我所有的交换机添加到一个数组中?…对不起