我必须在每一行上进行投射吗?

问题描述

| 我一直在通过在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 
    

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...