简体   繁体   English

将 NSArray 从 Objc 传递到 Swift 库

[英]Passing an NSArray from Objc to Swift Library

im trying to work with the following pods file in an objective c project:我正在尝试在目标 c 项目中使用以下 pods 文件:

https://cocoapods.org/pods/iOSDropDown https://cocoapods.org/pods/iOSDropDown

I've modified the coco file to ensure all attributes are public and have the @objc tag我已经修改了 coco 文件以确保所有属性都是公开的并且有 @objc 标签

However, I am attempting to perform the following Swift function in Objective c and I continue to receive the following error messages:但是,我试图在目标 c 中执行以下 Swift function 并且我继续收到以下错误消息:

Swift Code Im trying to execute in objective c Swift 代码我试图在目标中执行 c

dropDown.optionArray = ["Option 1", "Option 2", "Option 3"]

The objc code对象代码

NSArray * stringArray = @[@"Option 1", @"Option 2", @"Option 3"];
[_dropDown setOptionArray: stringArray];

And I continue to get the following error:我继续收到以下错误:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[iOSDropDown.DropDown setOptionArray:]: unrecognized selector sent to instance 0x7f8a90048800'

I understand that NSArray is a coco specific object that should transfer between swift and objc but im not sure why I am unable to set the optionArray property without crashing.我知道 NSArray 是 coco 特定的 object 应该在 swift 和 objc 之间传输,但我不确定为什么我无法设置 optionArray 属性而不崩溃。 Any help would be appreciated.任何帮助,将不胜感激。

It turns out that the swift object was of an array and not an NSArray.事实证明,swift object 是一个数组而不是 NSArray。 My solution to this was to create a helper variable in swift that takes in an NSArray and sets the optionArray var within swift:我对此的解决方案是在 swift 中创建一个辅助变量,该变量接受一个 NSArray 并在 swift 中设置 optionArray var:

@IBInspectable public var arraySetter = NSArray() {
    didSet{
        let objCArray = NSMutableArray(array: self.arraySetter)

        if let swiftArray = objCArray as NSArray as? [String] {
            // Use swiftArray here
            self.optionArray = swiftArray
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM