繁体   English   中英

Swift和Objective-C之间的NSInvalidArgumentException

[英]NSInvalidArgumentException between Swift & Objective-C

我正在开发一个同时使用Objective-C和Swift的项目。 我们正在使用网桥将它们连接在一起。

我有一个需要调用委托函数的快速类,但是当我尝试调用Objective-C函数时,我不断收到NSInvalidArgumentExceptions。

查看(快速):

// the-view.swift
//...
@objc public protocol YMUReceiptsContainerViewDelegate: Any {
    func receiptsContainerView(view: YMUReceiptsContainerView, didOpenAuthViewWithURL: NSString)
}
//...

func triggerUpdate() {
    // Calling this "triggerUpdate" function throws NSInvalidArgumentException
   // NOTE: self.delegate is the controller-view

    self.delegate?.receiptsContainerView(view:self, didOpenAuthViewWithURL:NSString(string: "https://yahoo.com"))
}

委托(目标C):

// the-view-controller.m
//...
- (void)receiptsContainerView: (YMUReceiptsContainerView *)view didOpenAuthViewWithURL:(NSString *)url {
    //do stuff...
}
//...

当我从Swift调用“ triggerUpdate()”函数时,我得到了NSInvalidArgumentException。 任何人都清楚我在做什么错吗? 我似乎无法使参数在Swift和Objective-C之间很好地发挥作用。

我得到了答案...在协议中定义参数的方式是错误的。 我需要将协议中的第一个参数更改为不需要标签。 在第一个参数之前添加“ _”可解决此问题。

// the-view.swift
//...
@objc public protocol YMUReceiptsContainerViewDelegate: Any {
    // Adding the "_" before "view" makes the parameter not require a label.
    func receiptsContainerView(_ view: YMUReceiptsContainerView, 
         didOpenAuthViewWithURL: NSString)
    }
//...

func triggerUpdate() {
    // Removed the "view" label when calling the function too...

    self.delegate?.receiptsContainerView(self, 
        didOpenAuthViewWithURL:NSString(string: "https://yahoo.com"))
}

只需进行一个小的更改,一切都将起作用。 问题的症结在于,当我在Objective-C中定义函数时,第一个参数没有标签。 然后,在我的代表中,我正在使用标签定义参数。 因此,参数没有从Swift正确传递给Obj-C。 在协议的第一个参数之前添加“ _”,可以使参数正确映射。

暂无
暂无

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

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