簡體   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