简体   繁体   中英

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM