为缺少弱链接祖先的类实例化类元数据
当我使用Xcode 12.5和Swift 5.4运行我的应用程序时。我在 pre-main 中崩溃了:
instantiating class metadata for class with missing weak-linked ancestor
相同的代码在Xcode 12.4和Swift 5.3上运行没有问题
回答
instantiating class metadata for class with missing weak-linked ancestor
阅读消息似乎表明,在启动时加载类元数据(“实例化类元数据”)时,运行时找不到关联的超类(“缺少弱链接祖先的类”)
这似乎得到了 Swift 代码库的证实。由于错误消息来自 Swift 运行时中的此函数:
static ClassMetadataBounds
computeMetadataBoundsForSuperclass(const void *ref,
TypeReferenceKind refKind) {
switch (refKind) {
case TypeReferenceKind::IndirectTypeDescriptor: {
auto description = *reinterpret_cast<const ClassDescriptor * const __ptrauth_swift_type_descriptor *>(ref);
if (!description) {
swift::fatalError(0, "instantiating class metadata for class with "
"missing weak-linked ancestor");
}
return description->getMetadataBounds();
}
}
调用自:
// Compute the bounds for the superclass, extending it to the minimum
// bounds of a Swift class.
if (const void *superRef = description->getResilientSuperclass()) {
bounds = computeMetadataBoundsForSuperclass(superRef,
description->getResilientSuperclassReferenceKind());
} else {
bounds = ClassMetadataBounds::forSwiftRootClass();
}
这是运行时寻找它正在加载的类的超类的地方。
经过一番挖掘,事实证明,在 Swift 5.3 上,您可以拥有
@available(iOS 13.0, *)
class A {
class B: HostingView<MyView> {
}
}
两者A并A.B会在iOS的12雨燕5.4被忽略(不知道是否发生变化或错误)A将被忽略,但A.B被加载。
因此,您可以通过以下方式解决崩溃:
@available(iOS 13.0, *)
class A {
@available(iOS 13.0, *)
class B: HostingView<MyView> {
}
}