Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting Class type

I know it's possible to define Class property which responds to a given protocol, like:

Class <MyProtocol> class = [object class];

But is there any way in Objective-C to cast Class type to my class?

Class unknownClass = [object class];
[((MyClass)unknownClass) myMethod]; // How can I cast Class to MyClass?
like image 980
msmialko Avatar asked Mar 21 '13 17:03

msmialko


People also ask

Which type of class is cast?

The cast() method of java. lang. Class class is used to cast the specified object to the object of this class. The method returns the object after casting in the form of an object.

What is type casting type?

Type casting is when you assign a value of one primitive data type to another type. In Java, there are two types of casting: Widening Casting (automatically) - converting a smaller type to a larger type size. byte -> short -> char -> int -> long -> float -> double.

What is type casting class 10?

Type casting is a way to convert a variable from one data type to another data type. For example, if you want to store a 'long' value into a simple integer then you can type cast 'long' to 'int'. You can convert the values from one type to another explicitly using the cast operator as follows − (type_name) expression.

How many types of casting are there?

There are two types of type casting: Widening Type Casting. Narrowing Type Casting.


1 Answers

What you are asking doesn't really make any sense.

unknownClass points to a class object. Class is just a type that can hold any pointer to a class object. You call a class method by sending a message to the class object.

Class, like id, turns off static type checking. That means the compiler won't complain that the object might not respond to the method. So you should just send a message to it. "Casting" doesn't make any sense. If you are getting en error that there is no interface that declares this method, then you got a completely unrelated problem that has nothing to do with types; instead the method is not declared in any visible header.

You say in comments to another answer that "I know that 'unknownClass' is in fact MyClass type." That makes your question make even less sense -- why not just use MyClass directly then? instead of unknownClass? Like [MyClass myMethod];

like image 93
newacct Avatar answered Sep 29 '22 16:09

newacct