Friday, April 15, 2011

How to cast an object in Objective-C

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!

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

    myEditController = [[SelectionListViewController alloc] init];
    ((SelectionListViewController *)myEditController).list = listOfItems;
    
    Yar : Or "Remember, Objective-C works like Java, just remember to add asterisks to variables that point to Obj-C objects."
  • ((SelectionListViewController *)myEditController).list
    

    More examples:

    int i = (int)19.5f; // (precision is lost)
    id someObject = [NSMutableArray new]; // you don't need to cast id explicitly
    
    Chris Hanson : In general this is correct; you don't need to cast id in message expressions. But when using dot syntax to access and set properties, you must use a concrete type, not just id, so the compiler knows what method invocation to actually generate. (It can differ for properties with the same name.)
  • Sure, the syntax is exactly the same as C - NewObj* pNew = (NewObj*)oldObj;

    In this situation you may wish to consider supplying this list as a parameter to the constructor, something like:

    // SelectionListViewController
    -(id) initWith:(SomeListClass*)anItemList
    {
      self = [super init];
    
      if ( self ) {
        [self setList: anItemList];
      }
    
      return self;
    }
    

    Then use it like this:

    myEditController = [[SelectionListViewController alloc] initWith: listOfItems];
    
  • Thanks for the quick replies everyone!

0 comments:

Post a Comment