Skip to content
This repository has been archived by the owner on Nov 9, 2021. It is now read-only.

Koshub/CoreDataStore

Repository files navigation

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.

About

CoreData Store Wrapper with Transactions

Resources

License

Stars

Watchers

Forks

Packages

No packages published