iiwi
iiwi 使设置 Core Data 栈(NSPersistentContainer)变得非常简单。在您的应用程序中,您需要创建 Core Data 模型,并使用自己的存储库子类化 iiwiAccess
。每个存储库负责从模型中 创建、检索 和 删除 一种类型的实体。每个存储库都应该有创建实体并设置所有必填和可选属性的函数。存在基于 主键 的查询。它的定义是通过实现泛型协议实现的。
示例
要运行示例项目,请克隆仓库,然后首先从 Example 目录运行 pod install
。
安装
iiwi 通过 CocoaPods 提供。要安装它,只需将以下行添加到您的 Podfile 即可:
pod 'iiwi'
使用
第一步是添加 import iiwi
语句。
然后我们需要通过指定其 名称 和可以找到它的 包 来初始化模型。iiwi.initialize(model: "iiwi", inBundle: .main)
还存在接受 bundle identifier(当模型在框架中时)或 URL 的初始化器。
仓库
应通过 仓库 访问实体。它们负责 创建、检索 和 删除 实体。
仓库是一個通用类,需要指定来自模型的实体 类型 和 主键查询。
class Repository<T: NSManagedObject, Q: PrimaryKeyQuery>
创建实体
创建实体是通过 Creator<T>
类完成的。Creator 是一个通用类,它指定了它将创建的实体类型。
为了创建实体,您必须调用 func create()
。
主键查询
当实体有主键时,我们可以简单地描述如何根据其实例名称和类型来检索实体。
public protocol PrimaryKeyQuery {
associatedtype EntityType: NSManagedObject
associatedtype KeyIndexType
var key: String { get }
var keyPredicateFormat: String { get }
var query: Query<EntityType> { get }
func entity(with: KeyIndexType) -> EntityType?
}
以下是如何根据 ID(INT64)查询实体的实现示例。
public class IdInt64Querable<T: NSManagedObject>: PrimaryKeyQuery {
public typealias EntityType = T
public typealias KeyIndexType = Int64
public let key = "id"
public let keyPredicateFormat = "id = %i"
public let query: Query<T>
init(context: NSManagedObjectContext) {
self.query = Query<T>(context: context)
}
}
为了避免实现 func entity(with: KeyIndexType) -> EntityType?
,有一个扩展可以用来。
extension PrimaryKeyQuery {
public func entity(with key: KeyIndexType) -> EntityType? {
return query.entities(with: NSPredicate(format: keyPredicateFormat, argumentArray: [key]), fetchLimit: 1, sortDescriptors: nil)?.first
}
}
如果实体 没有 主键,我们应该使用 NoPrimaryKeyQuerable
查询描述。
删除实体
删除实体是通过 Deletor<T>
类完成的。我们可以通过 func delete(entity: T)
删除单个实体或通过 func deleteAll()
删除所有实体。
iiwiAccess
所有模型实体的仓库都应该在您的 iiwiAccess
子类中定义和初始化。此类将负责 保存 和在上下文中 执行操作(NSManagedObjectContext)。
iiwiAccess子类的示例
import CoreData
import iiwi
public class DatabaseAccess: iiwiAccess {
let bookshelfs: BookshelfRepository
let authors: AuthorRepository
let books: BookRepository
override init(withContext context: NSManagedObjectContext) {
self.bookshelfs = BookshelfRepository(context: context)
self.authors = AuthorRepository(context: context)
self.books = BookRepository(context: context)
super.init(withContext: context)
}
public static let view: DatabaseAccess = {
return DatabaseAccess(withContext: iiwi.viewContext)
}()
static var newBackground: DatabaseAccess {
return DatabaseAccess(withContext: iiwi.newBackgroundContext())
}
}
额外访问
iiwi
类提供了对公共访问viewContext: NSManagedObjectContext
,以便能够根据您的要求进行调整。还有创建新后台上下文的功能:func newBackgroundContext() -> NSManagedObjectContext
。
作者
rogowskimark, [email protected]
许可
iiwi可在MIT许可下使用。有关更多信息,请参阅LICENSE文件。