Objective-C动态广播? [英] Objective-C dynamic_cast?
问题描述
Objective-C是否等效于C ++的dynamic_cast?
Is there an Objective-C equivalent of C++'s dynamic_cast?
可以使用以下方法伪造它:
It can be faked using this:
MyClass *safeObject = [object isKindOfClass: [MyClass class]]
? (MyClass *)originalObject : nil;
但这需要输入很多代码,即使我不需要经常输入.
But this is a lot of code to type, even if I don't need to type it often.
我有点生锈,所以这可能不太正确,但是我相信C ++中的等效条件是:
I am a bit rusty so this might not be quite right, but I believe the equivalent in C++ would be:
MyClass safeObject = dynamic_cast<MyClass>(orginalObject);
这里的上下文是一个块,其中参数定义为更通用的类的类型,但是在此块中,我知道"它是特定的子类.尽管如此,我不想只是用(MyClass *)originalObject
盲目地将其强制转换而忽略了理论上可能的错误.
The context here is a block where the parameter is defined as a type of a more generic class, but in this block I "know" it's a specific subclass. Nevertheless, I don't want to just cast it blindly with (MyClass *)originalObject
and ignore a theoretically possible error.
要清楚一点,虽然我很喜欢dynamic_cast
,但我也对能够安全处理此案的另一种方法感到满意.
To be clear, while I'd love a dynamic_cast
, I'd be happy with an alternate approach to safely handle this case as well.
推荐答案
如果您愿意使用Objective-C ++,则可以轻松编写以下代码:
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;
}
除了obj-c对象外,它的行为应与dynamic_cast<>
完全相同.
This should behave exactly as dynamic_cast<>
except for obj-c objects.
如果您要坚持使用香草Obj-C,则可以在NSObject
上使用类方法获得类似的行为:
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];
在两个版本中,如果强制转换失败,则结果值为nil
.
In both versions the resulting value is nil
if the cast fails.
这篇关于Objective-C动态广播?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!