2

Does Objective-C have a cast operator similar to 'as' operator in C# or the recommended way is to use isKindOfClass method to test the object and if yes cast the object to desired class?
In C# I do this:

Class1 o1 = obj as Class1;
if (o1 != null)
{
    // ...
}

In Objective-C should I go with this:

if ([obj isKindOfClass:[Class1 class]]) {
    Class1* o1 = (Class1*)obj;
    // ...
}
Ramy Al Zuhouri
  • 21,580
  • 26
  • 105
  • 187
iPDFdev
  • 5,229
  • 2
  • 17
  • 18

2 Answers2

1

You are right, isKindOfClass is the correct Objective-C way to check if an object is an instance of a given class or an instance of a subclass.

But have a look at the answers of

for various neat macros, categories and even a C++ template to provide a syntax that mimics the C++ dynamic_cast or the C# as operator.

Community
  • 1
  • 1
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
-1
class A { }
class B : A { }

A a = new A();
if(a.GetType() == typeof(A)) // returns true
{
}

A b = new B();
if(b.GetType() == typeof(A)) // returns false
{
}

or

test ts = new test();
            object ob = ts;

            if (typeof(test) == ob.GetType())
               {
                   return true;
               }
soheil bijavar
  • 1,213
  • 2
  • 10
  • 18
  • 1
    This *isn't* equivalent to `is` or `as` precisely because of this behavior; in C# `is` or `as` would indicate that a `B` is an `A`. – Servy Jul 08 '13 at 14:59