Choose the best explanation for why developers use the Repository pattern in iOS apps.
Think about how you keep your code organized and easy to change.
The Repository pattern acts as a middleman between data sources and the rest of the app. It hides details about where data comes from, so the app code stays clean and testable.
Consider an app where the UI shows a list of items fetched from a server. How does the Repository pattern help update the UI?
Think about efficient ways to keep the UI in sync with data.
The Repository can use callbacks or publishers to inform the UI only when new data arrives, making updates efficient and smooth.
Consider a Repository that holds network connections and caches data. What is a likely problem if it is not released correctly?
Think about what happens when objects keep references and never get freed.
If the Repository holds strong references and is never released, it causes memory leaks, which can slow down or crash the app.
Choose the best practice for sharing data managed by a Repository across different screens.
Think about how to keep data consistent and avoid duplication.
Sharing the same Repository instance ensures all view controllers see the same data and reduces bugs from inconsistent states.
Consider this simplified Swift code snippet:
protocol UserRepository {
func fetchUserName() -> String
}
class RemoteUserRepository: UserRepository {
func fetchUserName() -> String {
return "Alice"
}
}
class UserViewModel {
private let repository: UserRepository
init(repository: UserRepository) {
self.repository = repository
}
func displayName() -> String {
return "User: \(repository.fetchUserName())"
}
}
let repo = RemoteUserRepository()
let viewModel = UserViewModel(repository: repo)
print(viewModel.displayName())What will be printed?
Look at how the repository returns the user name and how the ViewModel uses it.
The RemoteUserRepository returns "Alice" for fetchUserName(). The ViewModel adds "User: " before it, so the output is "User: Alice".