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

时间:2023-01-15 14:25:47

I'm working on an iOS application written in Objective C that has an attached class written in Swift. When I try to call a in my Obj C AppDelegate.m, I don't get any errors, but the reply callback never fires.

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

My ObjC has the following methods:

我的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];

NSString * success = [SwiftClass swiftMethod];

My swift class looks like this:

我的快速课程看起来像这样:

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

In addition to the above code, I've made sure to include #import "ProjectName-Swift.h", as well as create a bridging header for the swift code.

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

Am I missing anything?

我错过了什么吗?

2 个解决方案

#1


6  

The swiftMethod is an instance method not a class method. You can call it like this:

swiftMethod是一个实例方法而不是类方法。你可以这样称呼它:

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

If you want to call it as class method then you need to declare it with class:

如果要将其称为类方法,则需要使用类声明它:

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

#2


0  

Also you have to add @objc before class and method

您还必须在课程和方法之前添加@objc

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

#1


6  

The swiftMethod is an instance method not a class method. You can call it like this:

swiftMethod是一个实例方法而不是类方法。你可以这样称呼它:

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

If you want to call it as class method then you need to declare it with class:

如果要将其称为类方法,则需要使用类声明它:

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

#2


0  

Also you have to add @objc before class and method

您还必须在课程和方法之前添加@objc

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