使用表示变量名称的字符串来设置变量
这是一个我知道可以简化的基本示例,但为了测试目的,我想以这种方式执行此操作。我想根据附加字符串设置一个变量(变量“cam0”和“pos1”已在类中声明)。附加字符串本质上是一个索引,我将迭代循环以将相机(cam0,cam1..)分配给不同的位置(pos0,pos1..)。
cam0 被定义为 UIImageView
pos1 被定义为 CGRect
这适用于名为 coverIndex 的 NSString 变量:
NSString* text = [[NSString alloc] initWithString:@""];
NSLog(@"%@",(NSString *)[self performSelector:NSSelectorFromString([text stringByAppendingString:@"coverIndex"])]);
我为 coverIndex 设置的正确字符串已记录到控制台。
现在回到我的 UIImageView 和 CGRect。我想让这个起作用。
NSString* camText = [[NSString alloc] initWithString:@"cam"];
NSString* posText = [[NSString alloc] initWithString:@"pos"];
[(UIImageView *)[self performSelector:NSSelectorFromString([camText stringByAppendingString:@"0"])] setFrame:(CGRect)[self performSelector:NSSelectorFromString([posText stringByAppendingString:@"1"])]];
我的错误是“请求转换为非标量类型”
这是我发现做这类事情(并使 NSLog 工作)的唯一方法,但我仍然相信有一种更简单的方法。
非常感谢您的帮助:)
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 (the variables "cam0" and "pos1" are already declared in the class). The appending string would essentially be an index, and i would iterate through a loop to assign cameras (cam0, cam1..) to different positions (pos0, pos1..).
cam0 is defined as an UIImageView
pos1 is defined as a CGRect
This works for a NSString Variable named coverIndex:
NSString* text = [[NSString alloc] initWithString:@""];
NSLog(@"%@",(NSString *)[self performSelector:NSSelectorFromString([text stringByAppendingString:@"coverIndex"])]);
The correct string that I set for coverIndex was logged to the Console.
Now back to my UIImageView and CGRect. I want this to work.
NSString* camText = [[NSString alloc] initWithString:@"cam"];
NSString* posText = [[NSString alloc] initWithString:@"pos"];
[(UIImageView *)[self performSelector:NSSelectorFromString([camText stringByAppendingString:@"0"])] setFrame:(CGRect)[self performSelector:NSSelectorFromString([posText stringByAppendingString:@"1"])]];
My error is "Conversion to non-scalar type requested"
This is the only way I found to do this sort of thing (and get the NSLog to work), but I still believe there is an easier way.
Thank you so much for any help :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 KVC,这是一项令人惊叹的技术,可以做到正是你想要的:
Use KVC, it's an amazing piece of technology that will do just what you want:
实现此目的的一种方法是在字典中创建相机并使用这些特殊的 NSString 来键入它。喜欢,
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,