Ric*_*evy 1 cocoa cocoa-touch objective-c
我一直在通过在Objective C中创建一个简单的应用程序来自学编程.今天,我遇到了一个问题,我必须编写一个方法,不知道它将获得什么类型的对象.在谷歌的帮助下,我很高兴发现了一种叫做"铸造"的东西.:)
我正在使用铸造:
- (void)aCustomViewControllerNeedsToChangeStuff:(id)viewController
{
((SpecialViewController *)viewController).aProperty = somethingInteresting;
((SpecialViewController *)viewController).anotherProperty = somethingElse;
((SpecialViewController *)viewController).yetAnotherProperty = moreStuff;
}
Run Code Online (Sandbox Code Playgroud)
我是否必须在这样的每一行上进行转换,或者是否有一种方法可以在方法范围内转换"viewController"一次,以使我的代码更整洁?
您可以将控制器转换为临时变量并使用它(还添加了类型检查 - 以防万一):
- (void)aCustomViewControllerNeedsToChangeStuff:(id)viewController
{
if ([viewController isKindOfClass:[SpecialViewController class]]){
SpecialViewController *special = (SpecialViewController *)viewController;
special.aProperty = somethingInteresting;
special.anotherProperty = somethingElse;
special.yetAnotherProperty = moreStuff;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
89 次 |
| 最近记录: |