Question on passing data to a VC


#1

I have gone through the complete book and am now making small apps for myself to strengthen my skills. I came across a problem that has to do with view controllers but also in part with classes and pointers. I hope this is the right place for my question.

I have a custom class “ProductClass” which has a subclass called “RatedProductClass”.

Now I’m using one view controller which should be able to display either the ProductClass data or the RatedProductClass data. The VC will never have both classes at the same time. Depending on when it is called in the app, the VC will be passed either an object of type ProductClass OR an object of type RatedProductClass. (this is decided at runtime).
The VC is a sort of summary-sheet, depending on what type of class it gets its data from, it is only slightly altered, so there is no need imho to make a dedicated view controller for my subclass.

My question is what is the right way to pass the object to the VC. I know there a probably many right ways but I want to know what is considered good programming manners. :slight_smile:

I figured out two ways to do this:

  1. Give the VC 2 properties. 1 for the superclass (ProductClass) and 1 for the subclass (RatedProductClass). As the VC never has both at the same time, I could check wich of the properties is not nil and act accordingly. This solution feels somewhat inelegant to me. It also does not make clear that there should only be either of the two properties at runtime.

  2. Give the VC 1 property of the superclass type.
    At runtime just assign the subclass object to the superclass property. As RatedProductClass is always a ProductClass, this should be possible. I’m getting a compiler warning (“incompatible pointer…”) if I do this but the app is running perfectly. I was able to shut up the compiler by doing a typecast when assigning the property, but I read somewhere else that typecasting in OOP should be avoided.

In my mind this solution has the advantage that it is clear to everybody that the VC should only hold one object, which has to be of type ProductClass (or subclasses?).

So how do you do this properly?

Is there something completely different that I’m not seeing or is my app design completely wrong?

Chris


#2

Number 2 is the way to go.

As for the incompatible-pointer warning, that’s not unexpected because you are assigning from ProductClass * to RatedProductClass * and an instance of ProductClass can be incompatible with an instance of RatedProductClass. However, it might be possible to do away with typecasting by redesigning the interface.


#3

Thanks ibex10 for clearing that up.

Cu
Chris