1. ホーム
  2. objective-c

[解決済み] Objective-Cでオブジェクトをキャストする方法

2022-02-10 13:46:49

質問

VB.NETでオブジェクトをキャストするのと同じように、objective-cでオブジェクトをキャストする方法はありますか?

例えば、以下のようなことをやろうとしています。

// create the view controller for the selected item
FieldEditViewController *myEditController;
switch (selectedItemTypeID) {
    case 3:
        myEditController = [[SelectionListViewController alloc] init];
        myEditController.list = listOfItems;
        break;
    case 4:
        // set myEditController to a diff view controller
        break;
}

// load the view
[self.navigationController pushViewController:myEditController animated:YES];
[myEditController release]; 

しかし、SelectionListViewControllerがFieldEditViewControllerを継承しているにも関わらず、SelectionListViewControllerクラスには「list」プロパティが存在し、FieldEditViewControllerにはないのでコンパイルエラーになる。

これは理にかなっていますが、myEditController を SelectionListViewController にキャストして、「list」プロパティにアクセスできるようにする方法はありますか?

例えばVB.NETではこうします。

CType(myEditController, SelectionListViewController).list = listOfItems

ありがとうございました。

解決方法は?

Objective-CはC言語のスーパーセットなので、タイプキャストはC言語と同じように機能することを忘れないでください。

myEditController = [[SelectionListViewController alloc] init];
((SelectionListViewController *)myEditController).list = listOfItems;