Objective-C dynamic_cast?

前端 未结 3 652
不思量自难忘°
不思量自难忘° 2020-12-05 11:19

Is there an Objective-C equivalent of C++\'s dynamic_cast?

It can be faked using this:

MyClass *safeObject = [object isKindOfClass: [MyClass class]]
         


        
相关标签:
3条回答
  • 2020-12-05 11:59

    If you're willing to use Objective-C++, you can write this pretty easily:

    template<typename T> inline T* objc_cast(id from) {
        if ([from isKindOfClass:[T class]]) {
            return static_cast<T*>(from);
        }
        return nil;
    }
    

    This should behave exactly as dynamic_cast<> except for obj-c objects.


    If you want to stick with vanilla Obj-C you can get similar behavior with a class method on NSObject:

    @interface NSObject (Cast)
    + (instancetype)cast:(id)from;
    @end
    
    @implementation NSObject (Cast)
    + (instancetype)cast:(id)from {
        if ([from isKindOfClass:self]) {
            return from;
        }
        return nil;
    }
    @end
    

    This version just isn't as nice to use since you have to say something like

    UIButton *button = [UIButton cast:someView];
    

    In both versions the resulting value is nil if the cast fails.

    0 讨论(0)
  • 2020-12-05 12:02

    Try this macro:

    #define objc_dynamic_cast(obj, cls) \
        ([obj isKindOfClass:(Class)objc_getClass(#cls)] ? (cls *)obj : NULL)
    

    And also don't forget to

    #include <objc/runtime.h>
    

    Use it like:

    MyClass *safeObject = objc_dynamic_cast(originalObject, MyClass);
    
    0 讨论(0)
  • 2020-12-05 12:14
    1. I don't think there is.
    2. I think the space for a bug is quite small here.
    3. But if you insist, a macro will do fine?
    0 讨论(0)
提交回复
热议问题