CoreDuck
示例
要运行示例项目,请克隆仓库,然后首先从 Example 目录运行 pod install
。
要求
- iOS 8.0+
- macOS 10.10+
- Swift 3.0+
安装
CoreDuck 通过 CocoaPods 提供。要安装它,只需在 Podfile 中添加以下行
pod 'CoreDuck'
初始化
import CoreDuck
// Init CoreDuck
let _ = CoreDuck.quack
如果在开发过程中想看到控制台中的错误
CoreDuck.printErrors = true
如果要指定CoreData *.xcdatamodeld文件的名字(默认为"CoreData")
/// Name of your *.xcdatamodel file
CoreDuck.coreDataModelName = "YourModelName"
上下文
/// Main NSManagedObjectContext of the app.
/// Primary usage is UIKit, works on the main thread of the app.
/// It's a singleton - always returns the same instance.
let context = NSManagedObjectContext.main
/// Background NSManagedObjectContext.
/// Returns new instance of NSManagedObjectContext each time you access this variable.
/// Use it for persisting changes to CoreData.
let backgroundContext = NSManagedObjectContext.main
保存数据
异步
NSManagedObjectContext.saveWithBlock({ context in
// your code goes here
}, completion: { success in
// completion block
})
同步
NSManagedObjectContext.saveWithBlockAndWait({ context in
// your code goes here
}, completion: { success in
// completion block
})
创建对象
在指定上下文中创建一个新的Core Data对象
if let newEntity = context.new(Entity.self) {
// your code goes here
}
在上下文中获取对象
获取上下文中的NSManagedObject实例的引用
if let entityInContext = context.get(entity) {
// your code goes here
}
删除对象
Entity.deleteAllObjects()
获取实体
基本搜索
以一个例子来说,假设你有一个名为Person的实体。你可以使用以下函数从你的持久存储中检索所有Person实体。
let people = context.findAll(entity: Person.self)
为了按特定属性对这些实体进行排序并返回,可以这样做
let people = context.findAll(entity: Person.self, sortedBy: "name", ascending: true)
如果你想要通过属性在Core Data中查找对象,可以使用以下函数
let people = context.findFirst(entity: Person.self, by: "name", with: "John")
let people = context.findFirst(entity: Person.self, by: "officeID", with: 7)
高级搜索
如果你想要执行更精确的搜索请求,可以使用谓词
let people = context.findAll(entity: Person.self, with: NSPredicate(format: "entityID IN %@", peopleIDs))
NSFetchedResultsController
let people = context.fetchAll(entity: Person.self, sortedBy: "entityID", ascending: true, delegate: self)
let people = context.fetchAll(entity: Person.self, with: predicate, sortedBy: "entityID", ascending: true, delegate: self)
let people = context.fetchAll(entity: Person.self, by: "officeID", with: 7, sortedBy: "entityID", ascending: true, delegate: self)
作者
- Maxym Skliarov https://github.com/skliarov
- Yura Voevodin https://github.com/yura-voevodin
许可协议
CoreDuck遵循MIT许可协议。有关更多信息,请参阅LICENSE文件。