首页 > 解决方案 > Swift 4.2 迁移后发送到实例的无法识别的选择器

问题描述

我刚刚将我的项目从 Swift 3.0 迁移到 Swift 4.2,我开始收到这个错误。

从多个类调用相同的方法,但只有一个抛出异常。任何想法在 Swift 迁移期间可能导致此问题的单个类中可能发生了什么变化?

2020-03-04 09:53:42.552405-0500 Lake Observer[13974:1234549]-[Lake_Observer.LocationChangeController reusablePickerViewController:didChooseValue:forCtrl:]:无法识别的选择器发送到实例 0x1040ca800 2020-03-04 09:53:402.554 Lake Observer [13974:1234549] *** 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“-[Lake_Observer.LocationChangeController reusablePickerViewController:didChooseValue:forCtrl:]:无法识别的选择器发送到实例 0x1040ca800”

这是发生异常的地方。(RecorderReusablePicker)

- (void) buttonIsPressed:(UIButton *)paramSender{

        NSMutableArray *retArray = [[NSMutableArray alloc] initWithCapacity:array.count];
        for (int i = 0; i < array.count; i++) {
            [retArray addObject:[NSNumber numberWithInteger:[genericPicker selectedRowInComponent:i]]];
        }
        [callingReference reusablePickerViewController:self didChooseValue:[[RecorderReusableResult alloc] initWithArray:retArray clearValue:NO] forCtrl:callingControlReference];
}

选择器是在这里创建的。(位置更改控制器)

func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {

    if (textField == editTextWaterBody) {
        let waterbodyArray: NSArray? = NSArray(objects: waterbodyNames)
        self.view.window?.rootViewController?.present(RecorderReusablePicker (dataArray: waterbodyArray as? [Any], widthArray: nil, inInitialIndexArray: [savedWaterbodyIndex], reference: self, andControlRef: editTextWaterBody, andTitle: "Please select your waterbody", showSelection: true, allowPanZoom: false), animated: true, completion: nil)
        return false
    }

    return true
}

以及从picker返回时的方法。

func reusablePickerViewController(_ reusablePickerViewController: RecorderReusablePicker!, didChooseValue retVal: RecorderReusableResult!, forCtrl outCtrl: Any!) {
    reusablePickerViewController.dismiss(animated: true, completion: nil)
}

同样,还有其他类具有完全相同的方法来从 Picker 创建和返回,但只有一个导致异常。

标签: iosswiftswift4.2

解决方案


改变

func reusablePickerViewController

@objc func reusablePickerViewController

从 Swift 3 到 Swift 4.2 的迁移改变了实例成员如何暴露给 Objective-C 的规则。在 Swift 3 中,它们是默认暴露的。在 Swift 4.2 中,您必须显式地公开它们;否则,Objective-C 看不到它们——这正是发生在你身上的事情。该方法存在,但 Objective-C 认为它不存在,因此它因无法识别的选择器异常而崩溃。


推荐阅读