ios - 无法从 Objective C 中的 swift 类调用方法

标签 ios objective-c swift

我正在开发一个用 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 代码创建桥接 header 。

我错过了什么吗?

最佳答案

swiftMethod 是一个实例 方法,而不是一个 方法。你可以这样调用它:

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

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

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

关于ios - 无法从 Objective C 中的 swift 类调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31799150/

相关文章:

ios - ios 7工具栏顶部边缘出现一个像素的细线

ios - UINavigationController pop 重置 Root View Controller 的框架

ios - 我想得到没有时间的今天日期

javascript - 多个文件以html形式上传

swift - 为 CollectionType(数组)添加排序功能

iphone - 从音乐库中获取歌曲列表后如何播放音乐文件?

ios - 传递数据以查看嵌入在容器 View 中的 Controller

ios - 将触摸事件传递给多个选项之一

swift - 强制 SKPaymentQueue 在后台线程上运行

swift - 无法使用 swiftyJSON 获取 json 对象