0

I have two tabs. And i want to set data from one tab to another. For example i have a code that switch to another tab:

func foundCode(code: String) {
    print("Code has been found: \(code)")
    // MySecondViewController.codeSetter(code);
    self.tabBarController?.selectedIndex = 1;
}

What is the best way to set it? Or maybe delegate this variable... But how ?

Arti
  • 7,356
  • 12
  • 57
  • 122

2 Answers2

0

Simple example for you using NSUserDefaults:

Store your data into first tab:

let testInstance = 1
NSUserDefaults.standardUserDefaults().setInteger(testInstance, forKey: "pass")

Now in another tab you can read that data from memory this way:

let instanceFromAnotherTab = NSUserDefaults.standardUserDefaults().integerForKey("pass")
print(instanceFromAnotherTab)

Hope it helps.

Dharmesh Kheni
  • 71,228
  • 33
  • 160
  • 165
  • can i do this with "segue" ?? – Arti Oct 02 '15 at 08:31
  • 1
    This is very bad practice, storing and reading from UserDefaults, every time you change between tabs. Better way: http://stackoverflow.com/a/21271948/3207979 – Dejan Skledar Oct 02 '15 at 08:56
  • Can you explain why this is a bad practice because I have never seen any down side of `NSUserDefaults`. @DejanSkledar – Dharmesh Kheni Oct 02 '15 at 09:24
  • I'll just say, that things already get unnecessarily complicated, when you try to save a Custom object to NSUserDefaults. – Dejan Skledar Oct 02 '15 at 09:29
  • This is even worse than using the appDelegate to pass data between controllers. – Abizern Oct 02 '15 at 10:41
  • 1
    here are apple allow to setIntegerForKey then why that is not good @abizen and dejan Skleder please review this: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/index.html#//apple_ref/occ/instm/NSUserDefaults/setInteger:forKey: And if realy not got then apple have to remove NSUserDefault from development side – Nitin Gohel Oct 02 '15 at 10:52
0

If you set a variable in your first controller like:

var code:String!

and in your function:

func foundCode(code: String) {
    print("Code has been found: \(code)")
    self.code = code

    // MySecondViewController.codeSetter(code);
    self.tabBarController?.selectedIndex = 1;
}

I think you should be able to access it in your second controller (i think the variables you declare in top are accessible in all of your classes)