Reputation: 25619
What I want to do is:
- (UIView *)getView:(UIView *)recycledView withClass:(Class)myClass
{
myClass *currentItem = (myClass*)recycledView;
....
}
I'm calling this function as follows:
[self getView:myView withClass:[SpecialView class]];
Getting a compilation error, any ideas if it's possible to achieve this?
Upvotes: 0
Views: 159
Reputation: 162712
Casting is a compilation only operation. You can't cast at runtime. At runtime, you can use isKindOfClass:
to determine class.
In general, the need for dynamic casting indicates a design problem in your code. Specifically, you aren't leveraging either inheritance or polymorphism correctly.
For this case, you might add:
+ (UIView*)recyleView:(UIView*)recycledView;
As a method to all of your SpecialView
classes (or it might be abstracted).
Upvotes: 5
Reputation: 47699
Sorry, you can't do it. The best you can do is cast to the declared type of myClass. Casts do not modify the objects, they simply declare the known (after checking) type of the existing object.
And there is no advantage to casting to a dynamic type, since all the compiler and JVM checks that occur based on the cast are static.
Upvotes: 1
Reputation: 18363
A cast happens during compilation, so attempting to cast to a type that's determined at run time (as in an Objective-C method call) is impossible.
Upvotes: 0