将WKNSURLRequest强制转换为?其他类型 [英] Crash casting WKNSURLRequest as? other type
问题描述
当我尝试投射WKNSURLRequest(以及其他类,全部来自WebKit框架)时,我遇到了严重崩溃。
I'm getting a hard crash when I try to cast WKNSURLRequest (and other classes, all from the WebKit framework).
例如在操场上:
import UIKit
import WebKit
final class Sigh: NSObject { }
NSClassFromString("NSObject") as? Sigh.Type
NSClassFromString("WKNSURLRequest") as? Sigh.Type
NSObject的类型转换有效(即返回 nil
),但WKNSURLRequest的强制转换会因EXC_BAD_ACCESS而崩溃-我以为它也会返回 nil
。
The cast from NSObject works (i.e. returns nil
), but the cast from WKNSURLRequest crashes with EXC_BAD_ACCESS - I would have assumed that it would return nil
as well.
有人知道是什么原因吗?
Anyone got any ideas what might be causing this?
推荐答案
WKNSURLRequest
不继承自 NSObject
@interface WKNSURLRequest : WKObject <NSCopying>
而 WKObject
是根类:
NS_ROOT_CLASS
@interface WKObject <WKObject>
不同于Java,Java的所有类必须从 Object
,Obj-C不需要所有类都可以从 NSObject
继承。
Unlike Java, where all classes must inerhit from Object
, Obj-C does not require all classes to inherit from NSObject
.
Swift<-> Obj-C桥显式支持 NSObject
并因此也支持其子类,但是我不确定它能否同样好地处理所有其他根对象。在导出方面(Swift类暴露于Obj-C),甚至不可能创建自己的根类。只需必须即可从Obj-C公开的快速类,它是从 NSObject
继承的,所以我想说该桥不是使用
The Swift<->Obj-C bridge has explicit support for NSObject
and thus also for its subclasses, but I'm not sure it can handle all other root objects equally well. On the export side (Swift classes being exposed to Obj-C) it's not even possible to make an own root class. A swift class that shall be exposed to Obj-C simply must inherit from NSObject
, so I'd say that the bridge has not been designed with arbitrary root classes in mind.
当然,这些都不能解释崩溃,这可能只是Swift编译器或Swift运行时中的一个简单错误。由于您不是静态引用类,而是仅通过名称来引用,所以一切都在运行时发生,而Swift运行时可能只假设 NSClassFromString
返回的是<$ c的子类$ c> NSObject ,然后当它尝试与该类进行交互时,它将在运行时失败,因为这种假设是完全错误的。在那种情况下,恕我直言仍然会是一个错误,但它会解释为什么会发生崩溃。
Of course, none of this explains the crash, which could just be a simple bug in the Swift compiler or the Swift runtime. As you don't reference the classes statically but just by their name, everything happens at runtime and the Swift runtime may just assume that whatever NSClassFromString
returns is a subclass of NSObject
and when it then tries to interact with that class, this will fail at runtime because this assumption is plain wrong. In that case it would still be a bug IMHO but it would explain why there is a crash.
这篇关于将WKNSURLRequest强制转换为?其他类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!