【问题标题】:Can't get Selector to work for my Swift Function无法让选择器为我的 Swift 函数工作
【发布时间】:2014-06-30 19:32:40
【问题描述】:

我有一个混合的 Swift 和 Objective C 应用程序。 swift 应用程序使用一些 ObjectiveC 库来处理 OAuth2 身份验证。其中一部分是在 OAuth2 对令牌的请求完成后对委托方法的回调。

以下代码正在使用我传入的选择器的 Objective C 库 (GTMOAuth2) 中执行:

if (delegate_ && finishedSelector_) {
  SEL sel = finishedSelector_;
  NSMethodSignature *sig = [delegate_ methodSignatureForSelector:sel];
  NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:sig];
  [invocation setSelector:sel];
  [invocation setTarget:delegate_];
  [invocation setArgument:&self atIndex:2];
  [invocation setArgument:&auth atIndex:3];
  [invocation setArgument:&error atIndex:4];
  [invocation invoke];
}

我想调用的函数在我的 swift viewController 中,看起来像这样:

func authentication(viewController: GTMOAuth2ViewControllerTouch, finishedWithAuth: GTMOAuth2Authentication, error: NSError)
{
    if (error != nil)
    {
        var alertView: UIAlertView = UIAlertView(title: "Authorisation Failed", message: error.description, delegate: self, cancelButtonTitle: "Dismiss")

        alertView.show()

    }
    else
    {
        // Authentication Succeeded
        self.mytoken = finishedWithAuth.accessToken
    }
}

我目前传入的选择器是:

let mySelector: Selector = Selector("authentication:viewController:finishedWithAuth:error:")

并且在此调用中用作参数:

let myViewController: GTMOAuth2ViewControllerTouch = GTMOAuth2ViewControllerTouch(authentication: auth, authorizationURL: authURL, keychainItemName: nil, delegate: self, finishedSelector: mySelector)

谁能告诉我为什么我的函数永远不会被调用?它似乎总是在创建 NSInvocation 的那一行失败。

我尝试了多个选择器字符串,但每一个似乎都失败了。我错过了什么吗?

我也试过在函数名称前加上“@objc”,但无济于事。

【问题讨论】:

  • 我认为应该是Selector("authentication:finishedWithAuth:error:"),但目前无法测试。
  • @Martin 的假设是正确的,我已经测试过了。选择器应该是Selector("authentication:finishedWithAuth:error:")

标签: objective-c oauth-2.0 swift selector gtm-oauth2


【解决方案1】:

Swift 方法

func authentication(viewController: GTMOAuth2ViewControllerTouch,
                  finishedWithAuth: GTMOAuth2Authentication,
                             error: NSError)

暴露在 Objective-C 中

-(void)authentication:(GTMOAuth2ViewControllerTouch *) viewController 
     finishedWithAuth:(GTMOAuth2Authentication *) finishedWithAuth
                error:(NSError *)error

表示选择器是

Selector("authentication:finishedWithAuth:error:")

通常,第一个参数名称不是选择器的一部分。唯一的例外 是init方法,其中第一个参数名被合并到Objective-C 方法名称。例如,Swift 初始化器

init(foo: Int, bar: Int) 

转换为 Objective-C 为

- (instancetype)initWithFoo:(NSInteger)foo bar:(NSInteger)bar

选择器是

Selector("initWithFoo:bar:")

【讨论】:

    【解决方案2】:

    测试了一下,果然如 Martin R 所说。

    let mySelector: Selector = Selector("authentication:finishedWithAuth:error:")
    

    swift函数的第一个参数从选择器上看通常是无名的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-26
      • 1970-01-01
      • 2012-04-22
      相关资源
      最近更新 更多