Câu hỏi phỏng vấn iOS
Câu hỏi

What is the difference between viewDidLoad and viewDidAppear ?

Câu trả lời

The methods viewDidLoad and viewDidAppear are both part of the UIViewController lifecycle in iOS development, but they serve different purposes and are called at different times during the lifecycle of a view controller.

viewDidLoad

  • Purpose: This method is called after the view controller's view has been loaded into memory. It is used for initial setup that only needs to happen once during the lifecycle of the view controller.
  • When it's called: It is called once when the view controller is first loaded into memory, either from a storyboard, XIB file, or programmatically.
  • Typical Use Cases:
    • Initializing data structures or variables.
    • Setting up views and controls that do not change.
    • Loading static data.
    • Adding subviews to the view hierarchy.
  • Example:
    swift Copy
    override func viewDidLoad() {
        super.viewDidLoad()
        // Initial setup code here
    }
  • Important Notes: Since viewDidLoad is called only once, it is not suitable for tasks that need to be repeated every time the view appears on the screen[1][2][3][7].

viewDidAppear

  • Purpose: This method is called after the view controller's view has been added to the app's view hierarchy and is visible on the screen. It is used for tasks that need to be performed every time the view appears.
  • When it's called: It is called every time the view appears on the screen, which can happen multiple times during the lifecycle of the view controller (e.g., when a modal view controller is dismissed and the view becomes visible again).
  • Typical Use Cases:
    • Starting animations.
    • Fetching or refreshing data.
    • Tracking analytics or user interactions.
    • Presenting modal view controllers.
  • Example:
    swift Copy
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        // Code to execute every time the view appears
    }
  • Important Notes: Since viewDidAppear can be called multiple times, any actions performed here should be repeatable and should not retain resources that are not released when the view disappears to avoid memory leaks[1][2][3][13].

Key Differences

  • Frequency: viewDidLoad is called once, while viewDidAppear is called every time the view appears on the screen.
  • Timing: viewDidLoad is called when the view is loaded into memory, whereas `viewDid...
junior

junior

Gợi ý câu hỏi phỏng vấn

middle

What are some pros and cons of Core Data?

middle

What's the difference between the frame and the bounds ?

senior

Explain how an autorelease pool works at the runtime level

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào