How to cast an object in Objective-C

Billy picture Billy · Mar 27, 2009 · Viewed 171.6k times · Source

Is there a way to cast objects in objective-c much like the way objects are cast in VB.NET?

For example, I am trying to do the following:

// 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]; 

However I am getting a compiler error since the 'list' property exists in the SelectionListViewController class but not on the FieldEditViewController even though SelectionListViewController inherits from FieldEditViewController.

This makes sense, but is there a way to cast myEditController to a SelectionListViewController so I can access the 'list' property?

For example in VB.NET I would do:

CType(myEditController, SelectionListViewController).list = listOfItems

Thanks for the help!

Answer

Jim Puls picture Jim Puls · Mar 27, 2009

Remember, Objective-C is a superset of C, so typecasting works as it does in C:

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