Swift 3 - 将数据传递回上一个viewcontroller

时间:2017-03-02 19:06:54

标签: ios objective-c swift3 delegates viewcontroller

我知道之前已经问过这个问题,但我似乎无法弄清楚为什么我在收到以下错误消息时,因为当点击按钮并将一个字符串从ViewControllerB传递给ViewController时应用程序崩溃答:

  

2017-03-02 12:42:02.485320 APPNAME [1111:2345678] - [ViewControllerA pressedNextButtonWithMessage:]:无法识别的选择器发送到实例0x11fd7eb90   2017-03-02 12:42:02.589949 APPNAME [1111:2345678]无效模式' kCFRunLoopCommonModes'提供给CFRunLoopRunSpecific - 中断_CFRunLoopError_RunCalledWithInvalidMode进行调试。此消息仅在每次执行时出现一次。   2017-03-02 12:42:07.586960 APPNAME [1111:2345678] *由于未捕获的异常终止应用程序' NSInvalidArgumentException',原因:' - [ViewControllerA pressedNextButtonWithMessage:]:无法识别的选择器发送到实例0x11fd7eb90'   * 第一次抛出调用堆栈:   (0x1819201c0 0x18035855c 0x181927278 0x181924078 0x18181e59c 0x100287824 0x1002878a0 0x18779e7b0 0x1879125ec 0x18779e7b0 0x18779e730 0x187788be4 0x187788d4c 0x18779e01c 0x18779db44 0x187798d8c 0x187769858 0x100159aec 0x187f56cb8 0x187f50720 0x1818ce278 0x1818cdbc0 0x1818cb7c0 0x1817fa048 0x18327d198 0x1877d4628 0x1877cf360 0x100077ef0 0x1807dc5b8)   libc ++ abi.dylib:以NSException类型的未捕获异常终止

我的应用程序是Swift 3和传统Objective-C之间的混合:

ViewControllerA.m

@interface ViewControllerA () <ViewControllerBDelegate>
@property (nonatomic, strong) NavViewController * navVC;

@end

@implementation ViewControllerA
- (void)viewDidLoad{
    ...
    self.navVC = [NavViewController instantiate]; // instantiate is a function that inits the storyboard and instantiates the viewcontroller from the NavViewController class
    ViewControllerB *vcB = [self.navVC.viewControllers firstObject]; // ViewControllerB is actually the rootviewcontroller of navVC
    vcB.delegate = self; 
    ...
}

- (void)pressedNextButton:(NSString *)message
{
    NSLog(@"Button worked: %@", message);
}
@end

ViewControllerB.swift

@objc protocol ViewControllerBDelegate {
    func pressedNextButton(message: String)
}

@objc class ViewControllerB: UIViewController, NSFetchedResultsControllerDelegate, UITableViewDataSource, UITableViewDelegate {

    var delegate: ViewControllerBDelegate?
    var passedMessage: String = "Pass this message back to ViewControllerA"

    @IBAction func nextButton(_ sender: UIBarButtonItem) { // this is the button that causes the app to crash
        self.delegate?.pressedNextButton(message: passedMessage) // app crashes after executing this line
    }
}

错误发生在

之后
  

self.delegate?.pressedNextButton(message:passedMessage)

已执行。另外,如果我删除了传递的消息&#39;来自代码的变量和相关参数,控制台确认正在执行的pressedNextButton函数没有问题(即我可以在控制台中看到日志,&#34; Button工作&#34;)。任何人都可以看到导致应用程序崩溃的原因以及我如何解决问题?

这是我的Connections Inspector for nextButton IBOutlet的屏幕截图: enter image description here

1 个答案:

答案 0 :(得分:2)

您的Objective-C和Swift邮件签名不匹配。你有两个选择:

修复Objective-C代码

在Objective-C代码中,更改

- (void)pressedNextButton:(NSString *)message

- (void)pressedNextButtonWithMessage:(NSString *)message

或者,修复Swift代码

在Swift代码中,更改

func pressedNextButton(message: String)

func pressedNextButton(_ message: String)