CoreDataStore 0.4.0

CoreDataStore 0.4.0

Kostiantyn Herasimov 维护。



  • 作者:
  • Kostiantyn Herasimov

CoreDataStore

CI Status Version License Platform

示例

要运行示例项目,请克隆仓库,然后首先从 Example 目录中运行 pod install

要求

安装

CoreDataStore 目前不能通过 CocoaPods 公共仓库获取。要安装它,只需将以下行添加到您的 Podfile 中

pod 'CoreDataStore'

示例

初始化存储

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
    }
}

扩展某些类型(这里为 User)以由某些存储表示(例如,您有某些 CDUser CoreData 实体)进行存储

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
    }
}

管理存储数据

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()
}

作者

科舒布

许可

CoreDataStore可以在MIT许可下使用。有关更多信息,请参阅LICENSE文件。