Andrew Lauer Barinov
Andrew Lauer Barinov

Reputation: 5754

Trouble casting UIView in iOS

I have a class called FooView which is a subclass of UIView and I'm trying to cast a UIView object into FooView.

I do this as follows

FooView *myView = (FooView*) MyViewController.view
NSLog(@"Leg is a class of %@",NSStringFromClass([myView class])); // Get UIView here.

The ivar of MyViewController is a UIView type.

I get a UIView result, any idea why this happens?

Upvotes: 0

Views: 631

Answers (2)

Henning
Henning

Reputation: 2710

You can create a loadView method in MyViewController that creates a FooView and sets it to self.view. It's for when you're not using a NIB.

Upvotes: 0

Jack Lawrence
Jack Lawrence

Reputation: 10782

Casting is a compile-time operation. It doesn't magically change the type of the object. It's mostly for compile time checking and a little runtime magic. myView is still a UIView, not a FooView.

These two lines in your question should give you your answer:

The ivar of MyViewController is a UIView type. I get a UIView result

All Objective-C objects have a pointer called isa that points to an object of type Class. Casting does not change that pointer, nor does it change the size of the object.

If you want to use a FooView, you need to change the property type in your controller and if you're using Interface Builder, change the type of the UIView in the inspector on the right.

Upvotes: 2

Related Questions