Just a quick one


This may be a very stupid question at this stage but can someone explain the following line of code to me;

HypnosisView *hv = (HypnosisView *)[self view];

I think I get the first part, I assume we are just creating an instance of the HypnosisView class. I don’t really understand the second bit though. I’m used to seeing alloc]init or so other init method?

Why is this one like this?

Any help would be great and please forgive me.


The view of this view controller is an instance of HypnosisView. However, the method view is declared as - (UIView *)view.

Thus, when you send this message to this view controller, it returns its HypnosisView instance but the compiler thinks it is a UIView *.

Since you are going to be sending this object a message that only HypnosisView responds to, we need to tell the compiler that it is in fact a HypnosisView, not a run of the mill UIView. This is what the (HypnosisView *) cast does.

Keep in mind, you cannot change the type of the object by doing this. For example, you couldn’t do this:

HypnosisView *v = (HypnosisView *)@"a string";

The type of a variable is just a hint to the compiler about the type of the object. The object is and will always be the type it was allocated as.


Oh I get it. Thanks so much for the reply! I feel pretty stupid now. :blush: