CoreDataStack in Swift
To create a Repository
Object:
let repository = Repository<User>()
Here User
is a subclass of NSManagedObject
.
To create new object use the method create(in:with:)
as follows:
let user: User = repository.create { (user) in
user.id = 2
user.name = "Test User"
}
By default Repository
class use writeContext
of CoreDataStack
, alternatively you can pass your own context. Like:
let user: User = repository.create(in: CoreDataStack.shared.mainContext) { (user) in
user.id = 2
user.name = "Test User"
}
To fetch the data use the method fetch(with:in:)
.
let users: [User] = try repository.fetch()
let predicate = NSPredicate(format: "name like '*3'")
let users: [User] = try repository.fetch(with: predicate)
To delete the rows from an entity use delete(entity:in:)
or delete(entities:in:)
or delete(in:with:in: )
methods.
repository.delete(entity: object)
or
repository.delete(entity: object, in: CoreDataStack.shared.mainContext)
repository.delete(entities: objects)
or
repository.delete(entities: objects, in: CoreDataStack.shared.mainContext)
Here you have to pass the Type of Entity from which you want to delete data.
let predicate = NSPredicate(format: "name like '*3'")
try repository.delete(in: User.self, with: predicate)
or
let predicate = NSPredicate(format: "name like '*3'")
try repository.delete(in: User.self, with: predicate, in: CoreDataStack.shared.mainContext)