Search code examples
iosnsmanagedobjectsuperclass

How to cast a super variable differently inside each of his children's?


The current status
I have a superclass named "GeneralCard" that is the super of many "CardsControllers".

Every class that inherits from "GeneralCard" has a different subclass of UIViewController that holds different NSManagedObjects subclasses -

(WhiteCardsController -->WhiteCard, RedCardsController --> RedCard ...).

I have a lot of functions that are actualy the same for all the managedObjects. so i want to group them in the general card.

The problem

I have created a "General" NSManagedObject called :

 NSManagedObject *currentCard.

Now on each View controller I am trying to cast :

self.currentCard = (WhiteCard*)self.currentCard;

So i will be able to use "WhiteCard" properties.

that dosent work as i keep getting errors like -

...Cards View Controllers/WhiteCardViewController.m:226: error: request for member 'letter' in something not a structure or union

As letter is not structured in NSManagedObject but it does in his WhiteCard subclass.

To the question *How can i share the same variable from the super but cast it differently on each vew controller ?*

Thanks a lot

shani


Solution

  • I would write an accessor method for each child class that returns the typecast object. Something like:

    - (WhiteCard *)myTypeCurrentCard {
        return (WhiteCard *)self.currentCard;
    }
    

    The parent class would have something like:

    - (GenericCard *)myTypeCurrentCard {
        return (GenericCard *)self.currentCard;
    }
    

    Within each controller class with these methods, the message [self myTypeCurrentCard] would return a object cast to the current type. This method does not guarantee the resulting object is actually that type of object, so care must be taken to insure no runtime errors occur by sending non WhiteCard objects white card specific messages.