0

I have two files

Question.m
Question.h

These two are written by Objective-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??

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much finally I make it to call swift function from objective-c. However there are still some problems for handling variables. stackoverflow.com/questions/44093341/…
Thanks for the upvote and accepting the answer @whitebear. I have answered the next question also. Hope it solves your problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.