-1

I have created a new xib coded with swift where the code calling this xib is done from a already made project in objective-c, what I want is to pass a string from the swift file to the previous objective-c view. I have tried with NSUserDafaults, with no real luck and I have thought to make a global variable and set it with the new code, the issue is that I'm not really familiar with obj-c. Could you help me to achieve this?

Amin Negm-Awad
  • 16,582
  • 3
  • 35
  • 50
Pedro.Alonso
  • 1,007
  • 3
  • 20
  • 41
  • 1
    NSUserDefaults will work for sharing a string, you should probably make a string property on the UIViewController you want to get to in objective-c and initialize that NSString property when you present it from your swift view, but here is a link to NSUserDefaults in swift that will help you solve your problem http://stackoverflow.com/a/25421987/3543861 – MSU_Bulldog May 23 '16 at 18:22
  • Just for my understanding: Do you really want to pass a value from Swift code to Objective-C code by using `NSUserDefaults`? – Amin Negm-Awad May 23 '16 at 20:02
  • Yes, I thought it will be easy but now is not having it I dunno why, @MSU_Bulldog what do you mean with make a string property and so on? – Pedro.Alonso May 23 '16 at 20:08

1 Answers1

0

Here is how to assign a property in your Objective-C class and assign it in your swift class.

in your obj-c class (named myObjClass in this example) in the .h file declare an NSString property:

@property (nonatomic, strong) NSString *myString;

Then in your swift class, assign the string before you present the view controller like this:

let myObjClass = self.storyboard?.instantiateViewControllerWithIdentifier("myObjClass") as? MyObjClass

// set its property
myObjClass.myString = "I am passing a string from Swift to Obj-C!"

self.navigationController?.pushViewController(myObjClass!, animated: true)

So in your myObjClass viewDidLoad method you can call this and it should print your string:

-(void) viewDidLoad {

    NSLog(@"My String: %@",self.myString);

}
MSU_Bulldog
  • 3,501
  • 5
  • 37
  • 73
  • Well I see it thanks, just one problem, I don't have a viewDidLoad method in the Obj-c class as it is a custom cell that does the action and is expecting the value. Is there any viewDidLoad equivalent? – Pedro.Alonso May 23 '16 at 20:55