我有一個大型應用程式,其中包含我們多年來撰寫的大量 ObjC 類。我正嘗試一次一點地遷移到 Swift,因為我不能冒可能破壞太多東西的大規模轉移的風險。
這是我當前問題的類層次結構:
OverFreeAnimalLimitViewController.swift (was originally ObjC) ->
FixBillingIssueViewController.swift (was originally ObjC) ->
BaseViewController.m ->
UIViewController
BaseViewController.m有:
@property(nullable, strong, nonatomic) IBOutletCollection(UIButton) NSArray<UIButton*> *appstring_buttons;
在情節提要中,我將所有按鈕附加到該集合,以便我可以通過編程方式設定它們的樣式,而不必在情節提要中一遍又一遍地進行相同的配置。
故事板中的底層 xml 代碼如下所示:
<connections>
<outletCollection property="appstring_buttons" destination="Kwf-Mv-Gis" id="ZzW-k6-Ydm"/>
<outletCollection property="appstring_buttons" destination="f7s-5H-81g" id="xRb-XN-pNs"/>
</connections>
當OverFreeAnimalLimitViewController和FixBillingIssueViewController是用 objc 撰寫時,這可以正常作業。
我已將它們轉換為 swift,現在應用程式在處理情節提要時崩潰了。當我運行該應用程式并且故事板嘗試附加所有 outlets 和 outletcollections 時,我得到:
“NSUnknownKeyException”,原因:“[<UIViewController 0x12b662370> setValue:forUndefinedKey:]:此類對于鍵 appstring_buttons 不符合鍵值編碼。”
我注意到錯誤訊息顯示的UIViewController不是OverFreeAnimalLimitViewController,所以我檢查了故事板,故事板正確地列出了這個視圖控制器的自定義類OverFreeAnimalLimitViewController。
我已經看到 swift 僅具有@IBOutlet和不明確具有@IBOutletCollection,因為當您想使用集合時,您只需使用帶有@IBOutlet注釋的陣列型別。但這是否意味著它會在嘗試使用底層時發生硬崩潰@IBOutletCollection?
如果OverFreeAnimalLimitViewController.swift我嘗試撰寫代碼來參考self.appstring_buttons,Xcode 會為我提供這個自動完成功能:

有沒有辦法解決這個問題,或者無法使用從帶有 @IBOutletCollections 的 ObjC 類擴展的 Swift 類?
uj5u.com熱心網友回復:
好的,我想通了。它與 Storyboard 的內部結構有關,與IBOutletCollection定義無關。
我在 Xcode 中創建了一個全新的專案來測驗這個問題,插座集合按預期作業,所以我知道這不是一個錯誤,應該有一個適合我的真實專案的解決方案。
一直困擾我的一件事是錯誤訊息說[<UIViewController 0x12b662370> setValue:forUndefinedKey:]用UIViewController而不是OverFreeAnimalLimitViewController。當我在問題一開始就看到這個問題時,我立即檢查了故事板以確保自定義類已設定,因為它看起來只是加載了一個裸 UIViewController 而不是我的子類。但我檢查了一下,它被設定在情節提要中,所以我將其排除在外。
是什么修復了它
我進入故事板并清除了自定義類設定,這樣它就回到了標準的 UIViewController。然后我OverFreeAnimalLimitViewController再次設定為自定義類。然后它起作用了。
它看起來像是當 Xcode 設定自定義類時,它查找參考的類,當它看到它是一個 swift 類時,它向故事板添加了一些額外的屬性,即customModule允許customModuleProvider它加載正確的類。
<viewController customClass="OverFreeAnimalLimitViewController" title="subscribe_to_sync" id="CMN-i2-ISu" sceneMemberID="viewController">
<viewController customClass="OverFreeAnimalLimitViewController" customModule="HerdBoss" customModuleProvider="target" title="subscribe_to_sync" id="CMN-i2-ISu" sceneMemberID="viewController">
之后,它能夠加載正確的視圖控制器子類,然后正確連接插座。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/533943.html
