【问题标题】:Can't call a method from a swift class in Objective C无法从Objective C中的swift类调用方法
【发布时间】:2015-08-04 01:11:16
【问题描述】:

我正在开发一个用 Objective C 编写的 iOS 应用程序,它有一个用 Swift 编写的附加类。当我尝试在我的 Obj C AppDelegate.m 中调用 a 时,我没有收到任何错误,但回复回调永远不会触发。

我的 ObjC 有以下方法:

- (void)application:(UIApplication *)application handleWatchKitExtensionRequest:(NSDictionary *)userInfo reply:(void(^)(NSDictionary *replyInfo))reply {

    NSString *success =[ApiController handleCall];
    //NSString *success =[self hello]; // This works if you swap it with the above method 
    //NSString *success = @"hello";    // when uncommented this also works.

    NSDictionary *dict = @{@"status" : success};

    reply(dict);
}

-(NSString *)hello{
    return @"hello";
}

NSString *success = [SwiftClass swiftMethod];

我的 swift 类如下所示:

@objc class SwiftClass {
    @objc func swiftMethod()->NSString{
        return "it works!"
    }
}

除了上述代码之外,我还确保包含 #import "ProjectName-Swift.h",并为 swift 代码创建一个桥接头。

我错过了什么吗?

【问题讨论】:

  • 您的代码不清楚 - 您对 swiftMethod 的调用实际上是在方法内吗?您是在 SwiftClass 的实例上调用它,还是从字面上调用 [SwiftClass swiftMethod]?后者不起作用,因为swiftMethod 不是类型方法。
  • “我没有收到任何错误,但只有代码。” ???

标签: ios objective-c swift


【解决方案1】:

swiftMethod 是 instance 方法而不是 class 方法。你可以这样称呼它:

NSString *success = [[SwiftClass new] swiftMethod];

如果你想调用它作为类方法,那么你需要用class声明它:

@objc class SwiftClass {
    @objc class func swiftMethod()->NSString{
        return "it works!"
    }
}

【讨论】:

    【解决方案2】:

    另外你必须在类和方法之前添加@objc

    @objc class MyClass: NSObjec {
       @objc func methodName() {
       }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多