不推荐使用Objective-C选择器的字符串文字,而是使用'#selector'

fuz*_*uzz 13 iphone objective-c ios swift

我有以下代码:

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
}
Run Code Online (Sandbox Code Playgroud)

我收到以下"警告" UIApplicationShortcutItem.respondsToSelector("new"),其中说:

不推荐使用Objective-c选择器的字符串文字,而是使用'#selector'

警告会自动替换代码:

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

但是这不能编译因为new()不可用.在这种情况下我应该使用什么?

Flo*_*ann 18

Xcode 7.3使用swift for iOS9.3/watchOS2.2/...

如果您以前使用过这行代码:

NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateResult:", name: "updateResult", object: nil)
Run Code Online (Sandbox Code Playgroud)

你现在应该使用这行代码:

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(InterfaceController.updateResult(_:)), name: "updateResult", object: nil)
Run Code Online (Sandbox Code Playgroud)

至少这是Xcode在我改变代码中的几个字符后提供给我的.当您遇到此错误时,似乎并不总能提供正确的解决方案.


Sco*_*son 8

创建一个协议,其唯一的原因是允许您构造适当的选择器.在这种情况下:

@objc protocol NewMenuItemHandling {
  func new()
} 
Run Code Online (Sandbox Code Playgroud)

您正在使用非正式协议(响应新选择器的对象)并将其转换为正式协议.

然后,您要在哪里使用选择器,您可以添加表达式:

#selector(NewMenuItemHandling.new)
Run Code Online (Sandbox Code Playgroud)