whitebear whitebear -4 years ago 105
Objective-C Question

Use delegate in objective c class to call swift method

I have two files

Question.m

Question.h


These two are written by Objecive-c

MainView.swift


This is written by Swift

Question Class has the delegate

@interface Question : NSObject{

id delegate;// put MainViewController here

- (void)trythisfunction{
[delegate test] // compiler doesn't find this method.
}
}


and I make class instance and put MainViewController as delegate of Question in MainViewController.swift

class MainViewController: UIViewController {
override func viewDidLoad(){
q = Question()
q.delegate = self // put self in delegate
}
func test(){
NSLog("test is OK")
}


However Compiler found error [delegate test]
Question.m:169:19: No known instance method for selector 'test:'

How can I solve this??

Answer Source

You need to make few changes.

Below class declaration doesn't compile because you can't declare variables inside interface.

    @interface Question : NSObject{

    id delegate;

    - (void)trythisfunction {
         [delegate test] 
    } 
    }

I have fixed above and the class now looks like this,

 # Question.h file
 #import <Foundation/Foundation.h>

 @interface Question : NSObject
 @property (nonatomic, strong) id delegate;
 @end

Below is the implementation of the class

 # Question.m file
 #import "Question.h"

 @implementation Question

 @synthesize delegate;

 - (void)trythisfunction{
     [delegate test];
 }
 @end

As we are integrating this swift and so we will need a Bridging Header whose content look like.

  #import "Test.h"

Finally in your swift class now you can import this class

import UIKit

class MainViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        let q = Test()
        q.delegate = self
    }
    func test(){
        NSLog("test is OK")
    }
}

And above code works like a charm.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download