简体   繁体   中英

Can't call a method from a swift class in Objective C

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.

My ObjC has the following methods:

- (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];

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.

Am I missing anything?

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

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!"
    }
}

Also you have to add @objc before class and method

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM