How to receive value from a variable of another Class

1

I have a variable in class Class1 and I want to use this variable in a function in class Class2

Screen1 has as its control the Class1 and screen2 has Class2

When calling screen2, Class2 will perform a function that has the class1 variable Class1     

asked by anonymous 10.11.2015 / 21:28

2 answers

1

I resolved through the prepareForSegue as suggested by @JadsonMedeiros I learned through this James Leist site

1) I created a follows by selecting the button on the screen and holding the CTRL key, dragged the screen2

1.1) In the StoryBoard field, I selected the following (arrow linking the screens) and the Attributes Inspector field in the Identifier field > WinningName

2) In class1 to pass the variable, I added the function

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "NomeDaSegue" {
            var svc = segue.destinationViewController as! Classe2

            svc.variavelDaClasse2_1 = variavelDaclasse1_1
            svc.variavelDaClasse2_2 = variaveldaClasse1_2.text
        }
    }

3) in Class2 where I will use the recovered variable

// dados da Classe1, não podem receber valores
    var variavelDaClasse2_1 : Int!
    var variavelDaClasse2_2 : String!


 print(variavelDaClasse2_2)
 print(variavelDaClasse2_1)
    
12.11.2015 / 02:50
2

There are several ways to do this, I believe the easiest way is to pass the value via the attribute.

Declare in the ViewController1 as an attribute the value you want to pass.

var numeroAleatorio = 4

In ViewController 2, create an attribute that receives the value of ViewController1.

var viewController1: ViewController!

Since you are NOT going to initialize the variable in this case, you MUST use the! which means that the variable is optional. If you do not use it, Swift will prompt you to initialize the variable, which is not what you intended, since it has already been started in ViewController1.

The type of this variable must be the class of your ViewController1.

Now, let's display your ViewController 2 ViewController.

let v2 = ViewController2()
v2.viewController1 = self

self.presentViewController(v2, animated: true, completion: nil)

Note that in

v2.viewController1 = self

You are pointing to the value of the viewController1 attribute that you created in your ViewController2 for your first view.

With the pointer to your first variable, it is extremely easy to access ANY attribute of the variable of the first view.

NSLog("%d", viewController1.numeroAleatorio)

If you start having two more views, you might want to search for Singleton.

I recommend that you also study ways to persist your information such as CoreData and NSUserDefaults.

    
10.11.2015 / 22:02