SafeFetching

This library offers a DSL (Domain Specific Language) to safely build predicates and requests to fetch a CoreData store. Also a wrapper around NSFetchedResultsController is offered to publish arrays of NSManagedObject to be used with a NSDiffableDataSource.

The documentation is built with docC. To read it, run Product โ†’ Build Documentation or hit โ‡งโŒƒโŒ˜D.

Note
This repository is a split of CoreDataCandy to offer the fetching features alone

Convenient and safe fetching

For any CoreData entity generated by Xcode, the only required step is to make it implement Fetchable.

final class RandomEntity: NSManagedObject {

    @NSManaged var score = 0.0
    @NSManaged  var name: String? = ""
}

extension RandomEntity: Fetchable {}

Then it’s possible to use the DSL to build a request. The last step can either get the built request as NSFetchRequest<RandomEntity> or execute the request in the provided context.

RandomEntity.request()
    .all(after: 10)
    .where(\.score >= 15 || \.name != "Joe")
    .sorted(by: .ascending(\.score), .descending(\.name))
    .setting(\.returnsDistinctResults, to: true)
    .nsValue

RandomEntity.request()
    .all(after: 10)
    .where(\.score >= 15 || \.name != "Joe")
    .sorted(by: .ascending(\.score), .descending(\.name))
    .setting(\.returnsDistinctResults, to: true)
    .fetch(in: context) // returns [RandomEntity]

Fetch update

When the entity type implements Fetchable, it’s possible to call the static updatePublisher function to create a publisher backed by a NSFetchedResultsController that will emit arrays of the entity. This is especially useful when working with a NSDiffableDataSource.

    let request = RandomEntity.request()
        .all(after: 10)
        .where(\.score >= 15 || \.name != "Joe")
        .sorted(by: .ascending(\.score), .descending(\.name))
        .nsValue

    RandomEntity.updatePublisher(
        sortingBy: .ascending(\.name),
        for: request,
        in: context
    ) // emits [StubEntity]

GitHub

View Github