我必须在每一行上投射吗?
我一直在通过用 Objective C 创建一个简单的应用程序从头开始自学编程。今天,我面临着一个问题,我必须编写一个不知道它将获得什么类型的对象的方法。在谷歌的帮助下,我很高兴地发现了一种叫做“casting”的东西。 :)
我像这样使用强制转换:
- (void)aCustomViewControllerNeedsToChangeStuff:(id)viewController
{
((SpecialViewController *)viewController).aProperty = somethingInteresting;
((SpecialViewController *)viewController).anotherProperty = somethingElse;
((SpecialViewController *)viewController).yetAnotherProperty = moreStuff;
}
我是否必须像这样在每一行上强制转换,或者有没有办法可以在方法的范围内强制转换“viewController”一次,以使我的代码更整洁?
I've been teaching myself programming from scratch by creating a simple app in Objective C. Today, I was faced with the issue that I had to write a method that didn't know what type of object it was going to get. With the help of Google, I was delighted to discover something called "casting". :)
I am using casting like so:
- (void)aCustomViewControllerNeedsToChangeStuff:(id)viewController
{
((SpecialViewController *)viewController).aProperty = somethingInteresting;
((SpecialViewController *)viewController).anotherProperty = somethingElse;
((SpecialViewController *)viewController).yetAnotherProperty = moreStuff;
}
Do I have to cast on every line like that, or is there a way I can cast "viewController" once in the scope of the method, to make my code neater?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以将控制器强制转换为临时变量并使用它(还添加了类型检查 - 以防万一):
You can cast your controller to temp variable and use it (also added type check - just in case) :
怎么样:
How about:
使用一个变量,例如,
而不是使用此变量来访问值,例如
Use one variable like
than use this variable to access value like