Skip to content
DeveloperMemos

Executing Some Code Only Once in viewDidAppear()

iOS, viewDidAppear(), Performance1 min read

In iOS development, the viewDidAppear() method is a critical component of the View Controller lifecycle. It's where developers often perform tasks that need to occur every time a view appears, such as updating UI elements or fetching fresh data. However, there are scenarios where you might want to execute code in viewDidAppear() only once, optimizing performance and preventing unnecessary repetition.

Whether it's initializing resources, setting up observers, or configuring interface elements, executing code in viewDidAppear() can be resource-intensive if not managed properly. Repetitive execution can lead to performance issues and even impact the user experience. Therefore, implementing strategies to ensure code runs only once within viewDidAppear() is crucial.

Here's a guide on how to achieve this efficiently:

1. Use Boolean Flags

One of the simplest and most effective ways to execute code only once in viewDidAppear() is by utilizing boolean flags. You can declare a boolean property in your View Controller class and toggle its value once the desired code has been executed. Subsequent invocations of viewDidAppear() can then check this flag before executing the code again.

1class MyViewController: UIViewController {
2 var codeExecuted = false
3
4 override func viewDidAppear(_ animated: Bool) {
5 super.viewDidAppear(animated)
6
7 if !codeExecuted {
8 // Execute code that needs to run once
9 codeExecuted = true
10 }
11 }
12}

2. Dispatch Once

Another approach is to use Grand Central Dispatch's dispatch_once functionality, which ensures that a block of code is executed only once during the app's lifecycle.

1class MyViewController: UIViewController {
2 private var onceToken: DispatchOnce = .init()
3
4 override func viewDidAppear(_ animated: Bool) {
5 super.viewDidAppear(animated)
6
7 DispatchQueue.once(token: &onceToken) {
8 // Execute code that needs to run once
9 }
10 }
11}

3. UserDefaults

If the code you want to execute once is related to user preferences or app settings, you can leverage UserDefaults to store a flag indicating whether the code has been executed.

1class MyViewController: UIViewController {
2 private let onceKey = "com.example.myViewControllerCodeExecuted"
3
4 override func viewDidAppear(_ animated: Bool) {
5 super.viewDidAppear(animated)
6
7 if !UserDefaults.standard.bool(forKey: onceKey) {
8 // Execute code that needs to run once
9 UserDefaults.standard.set(true, forKey: onceKey)
10 }
11 }
12}

4. Method Swizzling

Method swizzling is a more advanced technique where you dynamically exchange the implementation of a method at runtime. While powerful, it should be used judiciously and with caution - as it can lead to unexpected behavior if not implemented correctly. It's a pretty indepth topic, you can read more about method swizzling here.