如何解决我必须在每一行上进行投射吗?
| 我一直在通过在Objective C中创建一个简单的应用程序来从零开始教自己编程。今天,我面临着一个问题,即我不得不编写一种方法,该方法不知道将要获得什么类型的对象。在Google的帮助下,我很高兴发现称为“广播”的东西。 :) 我正在像这样使用cast:- (void)aCustomViewControllerNeedstochangeStuff:(id)viewController
{
((SpecialViewController *)viewController).aProperty = somethingInteresting;
((SpecialViewController *)viewController).anotherProperty = somethingElse;
((SpecialViewController *)viewController).yetAnotherProperty = moreStuff;
}
我是否必须像这样在每一行上进行强制转换,还是可以在方法范围内一次强制转换“ viewController \”以使代码更整洁?
解决方法
您可以将控制器转换为temp变量并使用它(还添加了类型检查-以防万一):
- (void)aCustomViewControllerNeedsToChangeStuff:(id)viewController
{
if ([viewController isKindOfClass:[SpecialViewController class]]){
SpecialViewController *special = (SpecialViewController *)viewController;
special.aProperty = somethingInteresting;
special.anotherProperty = somethingElse;
special.yetAnotherProperty = moreStuff;
}
}
,怎么样:
- (void)aCustomViewControllerNeedsToChangeStuff:(id)viewController
{
SpecialViewController * controller = (SpecialViewController *)viewController;
controller.aProperty = somethingInteresting;
controller.anotherProperty = somethingElse;
controller.yetAnotherProperty = moreStuff;
}
,使用一个变量,例如
SpecialViewController *tempController = (SpecialViewController *)viewController;
而不是使用此变量来访问类似的值
tempController.aProperty
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。