My project is combined with one viewcontroller written in objective C (objCViewController) and the other is written by swift (SwiftViewCOntroller). I have several variable NSString. I would like to update the string in objCViewController and access it in SwiftViewController by using delegate because I need to change between these two viewcontroller continuously and keep updating the string.
Here is the code:
objCViewController.h
#import <UIKit/UIKit.h>
@protocol MyDelegate <NSObject>
@end
@interface objCViewController : UIViewController{
NSString * stringbeingpassed;
}
@property (nonatomic, weak) id<MyDelegate> delegate;
@property (nonatomic, retain) NSString * stringbeingpassed;
@end
objCViewController.m
@implementation objCViewController
@synthesize delegate;
@synthesize stringbeingpassed;
- (void)updatestring {
//update string in this method
NSString * newstring = @"testing";
if (delegate != nil && [delegate respondsToSelector:@selector(stringUpdated:)]) {
[delegate stringUpdated: newstring];
}
}
bridging header.h:
#import "objCViewController.h"
SwiftViewController.swift:
protocol MyDelegate {
func stringUpdated(newMessage: String)
}
import UIKit
@objc class SwiftViewController: UIViewController, MyDelegate{
override func viewDidLoad() {
super.viewDidLoad()
}
func stringUpdated(newMessage:String) {
let newMessage = "sent string"
}
I have tried to use delegate but I have no idea how to use it. I'm completely new to swift and objective C
Q1. I would like to ask how can I assign my newstring to delegate in objCViewController and then pass it to SwiftViewController.
Q2. Another question is that how can I retrieve the data in delegate in SwiftViewController. What should I add?
Q3. Anything else that I have missed in defining delegate? Do I need to define it in both viewcontroller? Thank you.