Reputation: 99
How would I go about saving memory when loading items into a collection view from a database? Suppose I have over 10,000 items in a database that is being retrieved (including images) into a collection view with multiple labels also being retrieved from the database.
Would I have to retrieve only the first 20-50 items and then create a function to retrieve the next set when the user has passed through the data or would it have more to do with the images?
Upvotes: 0
Views: 333
Reputation: 306
Since iOS 10, you can prefetch data via the UICollectionViewDataSourcePrefetching
protocol.
I would encourage you to download the sample and have a play around but essentially it allows you to:
In terms of memory concerns, both table views and collection views employ object pooling to reuse cell views, populating them with new data.
More specifically this is achieved by calling dequeueReusableCell(withReuseIdentifier:for:) within your implementation of the UICollectionViewDataSource
method collectionView(_:cellForItemAt:)
An example of that is something along the lines of:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// Dequeues an existing cell if one is available,
// or creates a new one based on the registered class/nib.
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Cell.reuseIdentifier, for: indexPath) as? Cell else {
fatalError("Expected `\(Cell.self)` type for reuseIdentifier \(Cell.reuseIdentifier). Check the configuration in Main.storyboard.")
}
// Configure the cell for display.
return cell
}
Happy coding :D
Upvotes: 1
Reputation: 2465
You should retrieve the data only when need. Core Data already has this ready for you. Take a look at NSFetchedResultsController
.
Upvotes: 1