ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [iOS] UMC iOS 세미나 3주 차
    iOS/UMC 2022. 10. 5. 15:50

     

     

    오늘 학습한 내용

    💡 생명주기(Life Cycle)

     


    ✅ view의 생명주기는 왜 탄생했을까?

    View에서 생명주기는 화면에 보여졌다가 사라지는 주기를 뜻한다. PC의 한 화면에서 하던 작업을 모바일에서는 여러 단계로 분할해서 작업하게 되면서 view의 전환이 많아졌고, view가 전환되는 시점마다 다른 구현을 하기 위해서이다.

     

     

    View Controller의 생명주기는 Scene의 전환과 복귀에 따라 View Controller의 객체의 생성과 소멸이 발생한다.

     


     

    ✅ ViewController의 상태 변화

     

    Appearing Appeared Disappearing Disappeared
    ViewController가 스크린에 등장하기 시작한 순간부터 등장을 완료하기 직전까지 상태 ViewController가 스크린 전체에 완전히 등장한 상태 ViewController가 스크린에서 가려지기 시작해서 완전히 없어지기 직전까지의 상태 ViewController가 스크린에서 완전히 가려졌거나 혹은 퇴장한 상태

     


    ✅ ViewController의 상태 변화에 따라 호출되는 메서드들

     

    viewDidLoad( )

    - viewDidLoad는 ViewContorller의 모든 뷰들이 메모리에 로드되었을 때 호출된다.

       * 메소드가 호출되는 시점에서는 이미 outlet변수들이 모두 메모리에 위치하고 있다.

       * 클래스를 생성만 하고 present 등의 방식으로 뷰가 메모리에 로드되지 않는다면 이 메소드는 호출되지 않는다.

     

    - 화면이 보여지기 전 데이터를 뿌려주는 행위에 대한 코드를 작성할 수 있다.

    - 생명주기에서 딱 한 번 호출된다.

     

    viewWillAppear(_:)

    - viewWillAppear()는 뷰가 뷰 계층에 추가되고, 화면에 보이기 직전에 매 번 호출된다.

       * viewDidLoad()와 달리 화면 전환을 통해 다른 뷰로 이동했다가 돌아와도 재호출된다.

    ​   * 화면이 등장할 때마다 데이터를 불러오고 싶다면 / 애니메이션, 비디오, 사운드 등을 불러오고 싶다면 이 메서드 사용!

     

    viewDidAppear(_:)

    - View Controller의 뷰가 데이터와 함께 완전히 화면에 나타날 때 호출되는 메소드이다.

     

     

    viewWillDisappear(_:)

    - ViewController가 화면에서 사라지기 직전에 호출된다.

    - 해당 뷰를 통해 일어난 변화를 저장 / 뷰가 나타났을 때 조정됐던 다른 뷰들을 원래대로 돌려놓는 등의 작업을 수행 할 수 있다.

     

    viewDidDisappear(_:)

    - View Controller가 화면에서 사라진 직후에 호출된다.

    - 뷰가 사라질 때 멈춰야 할 작업들을 이 메소드에서 사용할 수 있다.

       * 주로 notifications 나 device sensor의 listening을 멈추는 기능

     

     

    UIViewController 공식 문서 & 블로그 참고

     

    Apple Developer Documentation

     

    developer.apple.com

     

    [iOS] ViewController의 특징과 생명주기

    전에 글에서 앱 전체의 상태변화와 앱의 생명주기에 대해 살펴보았습니다. https://blog.naver.com/soojin_...

    blog.naver.com

     

     

     

    코드를 통해 확인하기

        // 📌 viewDidLoad()
        // View가 메모리에 호출될 때 실행되는 메서드
        override func viewDidLoad() {
            super.viewDidLoad()
            print("viewDidLoad")
        }
        
        // 📌viewWillAppear()
        override func viewWillAppear(_ animated: Bool) {
            super.viewWillAppear(animated)
            print("viewWillApear")
        }
    
        // 📌viewDidAppear()
        override func viewDidAppear(_ animated: Bool) {
            super.viewDidAppear(animated)
            print("viewDidAppear")
        }
        
        // 📌viewWillDisappear()
        override func viewWillDisappear(_ animated: Bool) {
            super.viewWillDisappear(animated)
            print("viewWillDisappear")
        }
        
        // 📌viewDidDisappear()
        override func viewDidDisappear(_ animated: Bool) {
            super.viewDidDisappear(animated)
            print("viewDidDisappear")
        }

     


    ✅ 실습: 화면이 전환될 때 계산 결과를 보여주는 어플리케이션 만들기

     

    📌 viewController

    //
    //  ViewController.swift
    //  Week3
    //  View Life Cycle
    //
    //  Created by yeonsu on 2022/10/05.
    //
    
    
    import UIKit
    
    class ViewController: UIViewController {
    
        
        @IBOutlet weak var firstTextField: UITextField!
        @IBOutlet weak var secondTextField: UITextField!
        
        
        // 📌 viewDidLoad()
        // View가 메모리에 호출될 때 실행되는 메서드
        override func viewDidLoad() {
            super.viewDidLoad()
            print("viewDidLoad")
        }
        
        // 📌viewWillAppear()
        override func viewWillAppear(_ animated: Bool) {
            super.viewWillAppear(animated)
            print("viewWillApear")
        }
    
        // 📌viewDidAppear()
        override func viewDidAppear(_ animated: Bool) {
            super.viewDidAppear(animated)
            print("viewDidAppear")
        }
        
        // 📌viewWillDisappear()
        override func viewWillDisappear(_ animated: Bool) {
            super.viewWillDisappear(animated)
            print("viewWillDisappear")
        }
        
        // 📌viewDidDisappear()
        override func viewDidDisappear(_ animated: Bool) {
            super.viewDidDisappear(animated)
            print("viewDidDisappear")
        }
        
        
        @IBAction func buttonDidTap(_ sender: Any) {
            
            // UIStoryboard Main에 있는 SecondViewController에 접근
            guard let nextViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "secondViewController") as? secondViewController else {return}
            
            
            
            // ===== 덧셈을 해서 다음 View에 넘기는 로직 =====
            guard let firstNum = firstTextField.text else {return}
            
            
            guard let secondNum = secondTextField.text else {return}
            
            // String 타입으로 값이 넘어오기 때문에 형변환 필요
            // But, Int값이 들어오지 않으면 에러 발생! (신중히 사용)
            let result = Int(firstNum)! + Int(secondNum)!
            
            nextViewController.resultString = String(result)
            // =======================================
            
            
            nextViewController.modalPresentationStyle = .fullScreen
            
            present(nextViewController, animated: true)
        }
        
    }

     

    📌 secondviewController

    //
    //  secondViewController.swift
    //  Week3
    //
    //  Created by yeonsu on 2022/10/05.
    //
    
    import UIKit
    
    class secondViewController: UIViewController {
    
        var resultString = ""   // 덧셈 결과
        @IBOutlet weak var resultLabel: UILabel!
        
        
        override func viewDidLoad() {   //viewWillappear도 가능
            super.viewDidLoad()
            resultLabel.text = resultString
        }
      
    }

     

     

     

     


     

    [번외] 앱의 생명주기 확인해보기

    //
    //  SceneDelegate.swift
    //  Week3
    //
    // 앱의 생명 주기
    //  Created by yeonsu on 2022/10/05.
    //
    
    import UIKit
    
    class SceneDelegate: UIResponder, UIWindowSceneDelegate {
    
        var window: UIWindow?
    
    
        
        func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
            // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
            // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
            // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
            guard let _ = (scene as? UIWindowScene) else { return }
        }
    
        
        // 앱이 꺼졌어!
        func sceneDidDisconnect(_ scene: UIScene) {
            // Called as the scene is being released by the system.
            // This occurs shortly after the scene enters the background, or when its session is discarded.
            // Release any resources associated with this scene that can be re-created the next time the scene connects.
            // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
            print("sceneDidDisconnect")
        }
    
        func sceneDidBecomeActive(_ scene: UIScene) {
            // Called when the scene has moved from an inactive state to an active state.
            // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
            print("sceneDidBecomeActive")
        }
    
        
        // 앱이 곧 비활성화 될 거야!
        func sceneWillResignActive(_ scene: UIScene) {
            // Called when the scene will move from an active state to an inactive state.
            // This may occur due to temporary interruptions (ex. an incoming phone call).
            print("sceneWillResignActive")
        }
    
        func sceneWillEnterForeground(_ scene: UIScene) {
            // Called as the scene transitions from the background to the foreground.
            // Use this method to undo the changes made on entering the background.
            print("sceneWillEnterForeground")
        }
    
        
        // 앱이 백그라운드 상태에 도입했을 때
        func sceneDidEnterBackground(_ scene: UIScene) {
            // Called as the scene transitions from the foreground to the background.
            // Use this method to save data, release shared resources, and store enough scene-specific state information
            // to restore the scene back to its current state.
            print("sceneDidEnterBackground")
        }
    
    
    }

     

     

     

     

     

Designed by Tistory.