gpt4 book ai didi

objective-c - 防止 Obj-C 框架类命名与 Swift 中的 NSUnit 冲突

转载 作者:行者123 更新时间:2023-11-30 12:08:38 25 4
gpt4 key购买 nike

鉴于以下 Objective-C 类 Unit 存在于我的项目的嵌入式框架中:

@interface Unit : NSObject

// ...

@end

产品:

@interface Product : NSObject

@property(nonatomic, strong) NSArray<Unit *> *units;

//...

@end

我的主项目(这是一个 Swift 4 项目)中的以下代码:

extension Product {

var children: [NSObject] {
var children: [NSObject] = []

if let units = self.units {
for unit in units {
children.append(unit)
}
}

return children
}

}

在运行时产生以下崩溃和错误(发生在 for 循环行上):

Could not cast value of type 'Unit_Unit_' (0x618000452930) to 'NSUnit'
(0x7fff90c579b8).

有没有办法强制转换框架 Unit 类,以免与 NSUnit 类冲突?

我尝试了以下方法,但没有成功:

if let units = self.units as? [MyFramework.Unit] {
for unit in units { // <-- Crash occurs on this line
children.append(unit)
}
}

由于两个对象被命名为 Unit,我是否只是运气不好,无法将 Swift 与此 Objective-C 框架一起使用?

最佳答案

我能够通过执行以下强制转换找到解决方法:

if let units = self.units {
let unitsArray: [NSObject] = (units as NSSet).allObjects as! [NSObject]
for unit in unitsArray {
children.append(unit)
}
}

也许这会帮助其他人!

关于objective-c - 防止 Obj-C 框架类命名与 Swift 中的 NSUnit 冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46363572/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com