The repository pattern is a design pattern that provides a way to encapsulate the logic required to access data sources. By implementing a repository pattern over Core Data in Swift, you can separate your data access logic from your business logic, making your codebase cleaner and more maintainable.
Below is an example of how to implement a basic repository pattern for Core Data:
import Foundation
import CoreData
// Protocol defining the methods of the repository
protocol UserRepositoryProtocol {
func fetchAllUsers() -> [User]
func saveUser(name: String, age: Int)
}
// CoreData Entity class
@objc(User)
public class User: NSManagedObject {
@NSManaged public var name: String?
@NSManaged public var age: Int16
}
// Implementation of the repository
class UserRepository: UserRepositoryProtocol {
let context: NSManagedObjectContext
init(context: NSManagedObjectContext) {
self.context = context
}
func fetchAllUsers() -> [User] {
let request: NSFetchRequest = User.fetchRequest()
do {
return try context.fetch(request)
} catch {
print("Error fetching users: \(error)")
return []
}
}
func saveUser(name: String, age: Int) {
let user = User(context: context)
user.name = name
user.age = Int16(age)
do {
try context.save()
} catch {
print("Error saving user: \(error)")
}
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?