I’ve been teaching myself programming from scratch by creating a simple app in Objective C. Today, I was faced with the issue that I had to write a method that didn’t know what type of object it was going to get. With the help of Google, I was delighted to discover something called “casting”. 🙂
I am using casting like so:
- (void)aCustomViewControllerNeedsToChangeStuff:(id)viewController
{
((SpecialViewController *)viewController).aProperty = somethingInteresting;
((SpecialViewController *)viewController).anotherProperty = somethingElse;
((SpecialViewController *)viewController).yetAnotherProperty = moreStuff;
}
Do I have to cast on every line like that, or is there a way I can cast “viewController” once in the scope of the method, to make my code neater?
You can cast your controller to temp variable and use it (also added type check – just in case) :