我正在开发一个用 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/