Swiftpack.co - Koshub/CoreDataStore as Swift Package

Swiftpack.co is a collection of thousands of indexed Swift packages. Search packages.
See all packages published by Koshub.
Koshub/CoreDataStore 0.5.1
CoreData Store Wrapper with Transactions
⭐️ 2
🕓 4 years ago
iOS macOS
.package(url: "https://github.com/Koshub/CoreDataStore.git", from: "0.5.1")

CoreDataStore

CI Status Version License Platform

Example

To run the example project, clone the repo, and run pod install from the Example directory first.

Requirements

Installation

CoreDataStore currently is not available through CocoaPods public repo. To install it, simply add the following line to your Podfile:

pod 'CoreDataStore'

Example

Initialize store:

guard let modelURL = CoreDataStore.defaultModelURL() else { return }
guard let storeURL = CoreDataStore.defaultStoreURL() else { return }

let store = CoreDataStore(
    modelURL: modelURL,
    storeType: .sqlite(
        storeURL: storeURL,
        fileProtection: .complete
    )
)
store.initialize { (result) in
    switch result {
    case .success:
        // Now - use store
    default: break
    }
}

Extend some type (here User) to be stored by some store representation (for example, you have someCDUser CoreData entity):

struct User {
    var id = UUID().uuidString
    var firstName = UUID().uuidString
}

extension User: CoreDataStoreRepresentable, StoreIdentifiable {
    
    typealias RepresentationRequest = NSFetchRequest<CDUser>
    
    static var identifierKey: String { "id" }
    
    static func from(_ representation: CDUser, in context: NSManagedObjectContext) throws -> User {
        .init(id: representation.id ?? "", firstName: representation.firstName ?? "")
    }
    
    func update(_ representation: CDUser, in context: NSManagedObjectContext) throws {
        representation.id = id
        representation.firstName = firstName
    }
}

Manage store data:

let transaction = store.createTransaction()
do {
    try transaction.run { _, context in
        
        print("Existed: \n \(try context.fetch(User.self))")
        try context.delete(User.self)
        print("After delete: \n \(try context.fetch(User.self))")
        try context.insert([ User(), User(), User(id: "1", firstName: "Special") ])
        print("After insert: \n \(try context.fetch(User.self))")
        let special = try context.fetch(User.self, byID: "1")
        print(String(describing: special))
    }
    transaction.commit()
} catch {
    transaction.rollback()
}

Author

Koshub

License

CoreDataStore is available under the MIT license. See the LICENSE file for more info.

GitHub

link
Stars: 2
Last commit: 4 years ago
Advertisement: IndiePitcher.com - Cold Email Software for Startups

Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics