Instruction
In this lesson, we’ll go over threads, how to optimize them, and learn more about memory management.
Thread Optimization
Let’s begin by covering the fundamentals before diving into the exciting part of the lesson. So, what exactly is a thread? A thread is a small part of a computer program that runs independently but shares resources, like memory, with other threads in the same program. Think of it as a single task or a mini-program that helps the main program do multiple things at once, or what we call simultaneously, making the program faster and more efficient.
Main vs Background Thread
In iOS, threads can be categorized as either Main or Background threads. The Main thread is responsible for handling tasks related to updating the UI, such as refreshing the screen or updating a UI element. On the other hand, an iOS app can have multiple background threads, limited by the available device resources like CPU and RAM. Background threads are used for non-UI tasks like network requests and heavy computations. It is considered a best practice in iOS development to run as many tasks as possible in the background thread and run the final results to the main thread when updating the UI. Swift provides various methods like GCD (Grand Central Dispatch), Combine, and async/await to move tasks between the main and background threads. In this lesson, we will focus on the newest Swift feature, async/await, which is already widely used in new iOS apps.
Async/Await
To begin, Swift’s async/await syntax is a remarkable addition aimed at simplifying the process of writing and comprehending asynchronous code. By utilizing this feature, developers can write asynchronous code that resembles synchronous code, resulting in improved readability and maintainability. Now, let’s consider a typical Swift method that retrieves data and updates the user interface accordingly:
fetchData { data in
updateUI(with: data)
}
With async/await, you can avoid this nesting by writing code that looks more like sequential, synchronous code.
An async function is a function that can perform asynchronous tasks. To define an async function, you use the async keyword before the return type:
func fetchData() async -> Data {
// Asynchronous code to fetch data
}
func updateUI(with data: Data) async {
// Update UI
}
The await keyword is used to call an async function and wait for its result. This allows you to handle asynchronous results in a linear fashion. Here’s how you would use await with the fetchData function:
let data = await fetchData()
If we want to run these methods, we can use a Task:
Task {
let data = await fetchData()
await updateUI(with: data)
}
By default, both functions will be executed in a separate background thread. However, if we specifically want to ensure that the updateUI function runs on the main thread, we must annotate it with the @MainActor attribute. This will guarantee that the code within updateUI is executed on the main thread, which is crucial for updating the user interface in a responsive and efficient manner:
@MainActor
func updateUI(with data: Data) async {
// Update UI
}
Your application will now retrieve the information using a background thread, ensuring that the user interface remains responsive by updating it on the main thread. This will prevent any delays or unresponsiveness in the UI, providing a smoother experience for the users.
SwiftUI and ViewModel
SwiftUI aims to simplify the process of managing main and background tasks by minimizing repetitive code. By utilizing the new Observation framework, we can enhance a ViewModel by adding the @Observable attribute. This attribute ensures that all the properties within the ViewModel are automatically updated on the main thread. Consequently, SwiftUI views can effortlessly access and utilize these properties, guaranteeing that they are always up-to-date on the main thread.
Memory Management
The management of memory is a crucial aspect of programming, as it involves handling the life cycles of objects and releasing them when they are no longer necessary. The efficient management of object memory directly impacts the performance of an application. If an application fails to release unnecessary objects, it will gradually consume more memory, leading to a decline in performance.
Automatic Reference Counting (ARC)
Swift uses ARC to automatically manage memory. ARC keeps track of how many strong references an object has and automatically deallocates the object when there are no more strong references to it. This helps in managing memory without the need for manual memory management.
Retain Cycles and Their Impact
A retain cycle occurs when two or more objects hold strong references to each other, preventing them from being deallocated. This can lead to memory leaks, where memory that is no longer needed is not released, causing the application to consume more memory over time and potentially degrade performance.
Consider a scenario with two classes, Person and Apartment, where each instance holds a strong reference to the other:
class Person {
var apartment: Apartment?
deinit {
print("Person is being deinitialized")
}
}
class Apartment {
var tenant: Person?
deinit {
print("Apartment is being deinitialized")
}
}
var john: Person? = Person()
var apt: Apartment? = Apartment()
john?.apartment = apt
apt?.tenant = john
john = nil
apt = nil
In this example, neither Person nor Apartment will be deinitialized because they hold strong references to each other, creating a retain cycle.
Breaking Retain Cycles
- Using Weak References
To avoid retain cycles, you can use weak. Weak references do not increase the reference count of an object, allowing it to be deallocated.
class Person {
var apartment: Apartment?
deinit {
print("Person is being deinitialized")
}
}
class Apartment {
weak var tenant: Person?
deinit {
print("Apartment is being deinitialized")
}
}
var john: Person? = Person()
var apt: Apartment? = Apartment()
john?.apartment = apt
apt?.tenant = john
john = nil
apt = nil
In this revised example, Apartment holds a weak reference to Person, allowing both objects to be deallocated when they are no longer needed.
- Using Unowned References
Unowned references are similar to weak references but are used when the reference is expected to always have a value during its lifetime. This helps to avoid retain cycles without the overhead of optional unwrapping.
class Customer {
let name: String
var card: CreditCard?
init(name: String) {
self.name = name
}
deinit {
print("\(name) is being deinitialized")
}
}
class CreditCard {
let number: UInt64
unowned let customer: Customer
init(number: UInt64, customer: Customer) {
self.number = number
self.customer = customer
}
deinit {
print("Card #\(number) is being deinitialized")
}
}
var john: Customer? = Customer(name: "John Appleseed")
john?.card = CreditCard(number: 1234_5678_9012_3456, customer: john!)
john = nil
In this example, the CreditCard class holds an unowned reference to Customer, ensuring that the reference does not create a retain cycle.
Async/Await Memory Leaks
The usage of async and await can lead to a memory leak situation. This happens when a Task retains a strong reference to self, causing self to remain unreleased until the Task is done, creating a retain cycle. To break this cycle, a weak reference to self is required:
Task { [weak self] in
guard let data = await self?.fetchData() else { return }
await self?.updateUI(with: data)
}
Ensure that you do not use a guard let self statement, as this will cause the closure to hold a strong reference to self.