当 Key-Value 不起作用时的 Objective-C 点语法技巧?
我正在迭代一些对象,并尝试设置一些显然不喜欢键值编码的属性。 所以我无法在运行时创建一个字符串来表示“键”。
这行 ViewController 不会编译:
[self setValue:offsetX forKeyPath:[NSString stringWithFormat:@"myView%d.center.x", anInt]];
但我可以在一个可笑的 switch 语句中用点表示法设置这些属性:
myView1.center.x = offsetX;
还有其他方法可以解决这个问题吗? 也许创建一个像 myView(i).center.x 这样的访问器? 完全清楚这将是徒劳的,我什至尝试过: [NSString stringWithFormat:@"myView%d", anInt].center.x
无济于事...
I'm iterating through some objects and trying to set some properties that, apparently, don't like Key-Value coding. so I'm unable to create a string at runtime to represent the "key".
This line of ViewController won't compile:
[self setValue:offsetX forKeyPath:[NSString stringWithFormat:@"myView%d.center.x", anInt]];
but I can set these properties with dot notation in a ridiculous switch statement:
myView1.center.x = offsetX;
Is there another way to go about this? perhaps create an accessor like myView(i).center.x ? Knowing full well it was going to be futile, i even tried: [NSString stringWithFormat:@"myView%d", anInt].center.x
to no avail...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它无法编译的原因大概是因为 offsetX 是 int 或 float,而不是 NSNumber (在您的问题中给出编译器错误消息会很有帮助)。
然而,KVC 和 setValue:forKeyPath: 非常聪明,会自动为您从 NSNumber 转换,因此请使用:(
或适当的 numberWithFloat)。
The reason it wont compile is presumably because offsetX is an int or float, not an NSNumber (it would be helpful to give the compiler error message in your question).
However KVC and setValue:forKeyPath: is very clever and will automatically convert from an NSNumber for you, so use:
(or numberWithFloat as appropriate).