Memory Management
It's important to understand that when we load an element on screen, it takes up a portion of the device's RAM, which has different limits depending on the model.
This can become a common issue when loading a list of items, especially if each item contains an image, as each image can easily take up 1Mb of memory. So, if we load 5000 images, we could use up around 5GB, which would cause the system to abruptly close our app.
To prevent this, we can use the List
element, which loads its content into memory as it appears on screen. This is different from components like ScrollView
, which will load every single element at once.
Using List
@State var groceryList: [String] = [
"Potato",
"Tomato",
"Cucumber",
"Chicken",
"Cookies",
"Water",
"Apple juice",
"Salmon"
]
var body: some View {
List {
ForEach(groceryList, id: \.self) { item in
Text(item)
}
}
}
Text(item)
is just an example. Each item can be represented by any other view. For example, we can use a Button
to detect which item the user has selected:
List {
ForEach(groceryList, id: \.self) { item in
Button(action: {
print("Iteme selected: \(item)")
}, label: {
Text(item)
})
}
}
Be the first to comment