2016-03-23 61 views
12

我有以下代碼:使用字符串字面的Objective-C選擇器已被棄用,使用「#selector」,而不是

func setupShortcutItems(launchOptions: [NSObject: AnyObject]?) -> Bool { 
    var shouldPerformAdditionalDelegateHandling: Bool = false 

    if (UIApplicationShortcutItem.respondsToSelector("new")) { 
     self.configDynamicShortcutItems() 

     // If a shortcut was launched, display its information and take the appropriate action 
     if let shortcutItem: UIApplicationShortcutItem = launchOptions?[UIApplicationLaunchOptionsShortcutItemKey] as? UIApplicationShortcutItem { 
      // When the app launched at the first time, this block can not called. 
      self.handleShortCutItem(shortcutItem) 

      // This will block "performActionForShortcutItem:completionHandler" from being called. 
      shouldPerformAdditionalDelegateHandling = false 
     } else { 
      // normal app launch process without quick action 
      self.launchWithoutQuickAction() 
     } 
    } else { 
     // Less than iOS9 or later 
     self.launchWithoutQuickAction() 
    } 

    return shouldPerformAdditionalDelegateHandling 
} 

我得到UIApplicationShortcutItem.respondsToSelector("new")下面的「警告」,其中說:

使用字符串字面的Objective-C選擇器已經過時,用「#selector」,而不是

警告並自動替換代碼:

UIApplicationShortcutItem.respondsToSelector(#selector(FBSDKAccessToken.new))

然而,這並不編譯,因爲new()是unavailabe。 我應該在這種情況下使用什麼?

+0

檢查這個......可能是你得到的東西http://stackoverflow.com/questions/36147831/syntax-selector-swift-2-2 –

+0

爲什麼您選擇'new'測試?我沒有看到在這裏發送'new'消息的任何代碼。 –

回答

16

的Xcode 7.3 iOS9.3/watchOS2.2/...

如果您以前使用此:

然後,你要使用的選擇,你可以添加表情行代碼:

NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateResult:", name: "updateResult", object: nil) 

你現在應該使用這行代碼:

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(InterfaceController.updateResult(_:)), name: "updateResult", object: nil) 

至少這是Xcode中給了我後,我周圍的代碼幾個字符改變。似乎它並不總是提供正確的解決方案,當你出現這個錯誤。

+1

這對我工作,比選定的答案更好。 – ded

+1

Upvoted - 這是完美的! –

+0

'button.addTarget(self,action:#selector(ViewController.onClickStart),for:.touchUpInside)'我使用這個。謝謝 ! @Florian Uhlemann –

1

在這種特殊的情況respondsToSelector,在那裏你沒有現有的方法可以進行函數引用相關聯,這樣寫:

UIApplicationShortcutItem.respondsToSelector(Selector("new")) 

你還是會得到一個警告(你不應該和我我提出了一個反對它的錯誤),但它會是一個不同的警告,你可以忽略它。

+2

真正的笑話是你應該能夠通過說'#selector(NSObject.new)'來解決這個問題,因爲這真的是你的意思。但是當你這麼說的時候,你會得到一個錯誤而不是一個警告! – matt

+2

@gotnull以下是蘋果對我的錯誤報告的回覆:「工程部門已確定您的錯誤報告(24815319)與另一個問題(24791200)重複,並且將被關閉。」請隨意堆放:重複越多越好。 – matt

6

創建一個協議,其唯一存在的理由是讓你構建適當的選擇。在這種情況下:

@objc protocol NewMenuItemHandling { 
    func new() 
} 

你正在服用的非正式協議(即響應新選擇的對象),使之成爲一個正式的協議。使用快捷

#selector(NewMenuItemHandling.new) 
+1

Devilishly偷偷摸摸。 – matt

+0

我不知道我會稱它爲鬼祟。 Objective-C基本上依賴於非正式的協議(如果你願意,可以使用Duck Typing)。 Swift希望對協議更正式一些。所以你已經採取了一個非正式的協議,並告訴斯威夫特它存在:-) –

0

總之,每一個 「選擇器:功能或對象」 現在是 「選擇器:#selector(class.funtion(_ :))」 用於任何。

相關問題