Sharing Values (Variables) in Different View Controllers

Asked 2 years ago, Updated 2 years ago, 111 views

I would like to share the values between the two ViewControllers in this image, but the 100 that should appear on the ViewController 2 label does not appear, and the label that should disappear remains displayed.

Status (Image)
https://teratail.storage.googleapis.com/uploads/contributed_images/997de6dc17a7b4a91f423c6487f0ba85.png

The order is
1. Declare tast in AppDelegate.swift
2.In ViewController, put 100 in appDelegate.test
3. Receive the test as test1 in ViewController 2 and display it on the label
That's what I thought.

It doesn't matter if the method is a little different, so please tell me how to share values with different View Controllers.

[appDelegate.swift]

import UIKit

@UIAapplicationMain
classAppDelegate:UIResponder,UIApplicationDelegate{

var window —UIWindow?
vartest —String?


func application(_application:UIApplication, didFinishLaunchingWithOptions launchOptions:[UIApplicationLaunchOptionsKey:Any]?) ->Bool{
    // Override point for customization after application launch.
    return true
}

func applicationWillResignActive(_application:UIApplication){
    // Sent when the application is about to move from active to inactive state. This can account for certificate of temporary interventions (succ as an incoming phone call or SMS message) or when the user quits the application and it starts the transition to the background state.
    // Use this method to pauseongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

func applicationDidEnterBackground(_application:UIAapplication){
    // Use this method to release shared resources, save user data, invalidate timers, and store through application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called installed of applicationWillTerminate: when the user quits.
}

func applicationWillEnterForeground(_application:UIAapplication){
    // Called as part of the transition from the background to the active state; here you can do many of the changes made on entering the background.
}

func applicationDidBecomeActive(_application:UIApplication){
    // Restart any tasks that were pressed (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

func applicationWillTerminate(_application:UIApplication){
    // Called when the application is about to terminate.Save data if approve.See also applicationDidEnterBackground:.
}

}

ViewController.swift

import UIKit

classViewController:UIViewController {
@IBOutlet weak var B: UIButton!
@IBOutlet weak var L:UILabel!
@ IBAction funcBA(_sender:AnyObject){
    let appDelegate: AppDelegate=UIAapplication.shared.delegate as! AppDelegate
    appDelegate.test=String(100)
}




override func viewDidLoad(){
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from anib.
}

override funcdidReceiveMemoryWarning(){
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


}

ViewController 2.swift

import UIKit

classViewController 2:UIViewController {
vartest1 = String()

@IBOutletweakvartetststs:UILabel!
@IBOutlet weak varfsg:UIButton!
@IBOutlet weak varerg:UILabel!

@ IBAction funcsjrsm(_sender:AnyObject){
    tetststs.text=String(test1)
    print(test1)
    if test1 == String(100) {
        erg.isHidden=true

    }
}
override func viewDidLoad(){
    super.viewDidLoad()
    let appDelegate: AppDelegate=UIAapplication.shared.delegate as! AppDelegate

    vartest1 = appDelegate.test


    // Do any additional setup after loading the view.
}

override funcdidReceiveMemoryWarning(){
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
}

swift swift2 swift3

2022-09-30 10:27

1 Answers

Let's not talk about details, but it's here that's fundamentally bad.

override func viewDidLoad(){
    super.viewDidLoad()
    let appDelegate: AppDelegate=UIAapplication.shared.delegate as! AppDelegate

    vartest1 = declaring local variable for appDelegate.test//###`viewDidLoad()`


    // Do any additional setup after loading the view.
}

One line in part ### of the comment newly declares the local variable test1 to be used only in the body of viewDidLoad(), which is completely different from the instance property test1 declared by var test1=String().

(If you built the code exactly as you asked, the Xcode should have alerted you.The current Xcode warning is very well-crafted and should not be ignored at all.)

self.test1=appDelegate.test???" should cure the most important part of your question, but if you say viewDidLoad(), you may not be able to copy the correct value depending on the order of execution.Variables with the same name may appear elsewhere and may be confusing.

Anyway, why don't you look directly at the common data location (AppDelegate for your code) for data accessed by multiple ViewControllers?You don't have to wonder where and when to copy.

import UIKit

classViewController 2:UIViewController {
    //### Keep AppDelegate accessible
    var appDelegate:AppDelegate {
        US>return UIAapplication.shared.delegate as!AppDelegate
    }

    @IBOutletweakvartetststs:UILabel!
    @IBOutlet weak varfsg:UIButton!
    @IBOutlet weak varerg:UILabel!

    @ IBAction funcsjrsm(_sender:AnyObject){
        tetststs.text=appDelegate.test???"//### Common data directly refer to the value in `appDelegate`
        print(appDelegate.test???")
        if appDelegate.test==String(100){
            erg.isHidden=true

        }
    }
    override func viewDidLoad(){
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        //### You don't have to do anything in `viewDidLoad()`
    }

    override funcdidReceiveMemoryWarning(){
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

If the app is getting bigger, you may say that it's better to put it in a different place (class) from AppDelegate, but if you make it like the one above, it won't be such a big fix.Try it.

By the way, if there is a high possibility that you will continue to use the QA site frequently in the future, I think you should get into the habit of making the name a little more meaningful (for example, in a trial project to check the operation).To be honest, B or L makes it difficult to get your questions across because you have no idea what button or label it is for.


2022-09-30 10:27

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.