I have a UIView called Product, which contains a sub UIView called Postcode.
In the Postcode UIView i have a simple form (one UITextField and one UIButton).
When the UIButton is clicked a method (called -storeData) is run inside postcode view … which works as intended.
Now inside storeData I would like to call a method in the superview Product.
This is what i tried doing, but im getting a warning:
if ([[self superview] class] == [ProductView class]) {
ProductView *p = [self superview];
[p handlePostChange];
}
// Get this warning from this line ProductView *p = [self superview];
PostView.m:124:28: Incompatible pointer types initializing
‘ProductView *__strong’ with an expression of type ‘UIView *’
The call to
[self superview]returns aUIViewpointer. You are trying to do the equivalent of:The compiler has no way to know that at runtime,
viewwill really be of typeProductView. This is why the compiler complains.The solution, as was stated, is to use a cast:
The cast tells the compiler “hey, don’t worry, I know what I’m doing. It really is a
ProductView“. Of course if you are wrong, the app will most likely crash at runtime.The following is perfectly fine:
This is safe, gives no warning, and requires no cast. This works because it is known that
ProductViewis a subclass ofUIView.