Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Objective-C, given an id, how can I tell what type of object it points to?

Tags:

objective-c

Objective-C newbie question. Given the following (fictional) code:

id mysteryObject = [anotherObject mysteriousMethod]; 

How can I determine at runtime what class mysteryObject is?

like image 493
Justicle Avatar asked Jul 14 '09 04:07

Justicle


People also ask

How do I find the type of a variable in Objective-C?

Using - (BOOL)isKindOfClass:(Class)aClass in this case would result in TRUE both times because the inheritedClass is also a kind of the superClass. isMemberOfClass: will return NO when dealing with subclasses.

What is id type in Objective-C?

id is the generic object pointer, an Objective-C type representing "any object". An instance of any Objective-C class can be stored in an id variable.

What is id in C?

In C language, an identifier is a combination of alphanumeric characters, i.e. first begin with a letter of the alphabet or an underline, and the remaining are letter of an alphabet, any numeric digit, or the underline.

How do you declare an object in Objective-C?

Creating a new object in Objective-C is usually a two-step process. First, memory has to be allocated for the object, then the object is initialized with proper values. The first step is accomplished through the alloc class method, inherited from NSObject and rarely, if ever, overridden.


1 Answers

You can use isKindOfClass or isMemberOfClass

For example:

if ([foo isMemberOfClass:[NSBar class]])

like image 83
Roland Rabien Avatar answered Sep 21 '22 17:09

Roland Rabien