测试已测试 | ✗ |
Lang语言 | SwiftSwift |
许可协议 | MIT |
发布最后发布 | 2017年6月 |
SwiftSwift 版本 | "3.0" |
SPM支持 SPM | ✗ |
由 Minty Water Ltd 维护。
[](https://travis-ci.org/Chris
Wunsch/CWCoreData)
此库需要以下内容
CWCoreData 通过 CocoaPods 提供。要安装它,只需将以下行添加到您的 Podfile 中
pod "CWCoreData"
Minty Water Ltd
Chris Wunsch,[email protected]
CWCoreData 在 MIT 许可协议下可用。有关更多信息,请参阅 LICENSE 文件。
我们接受 pull request!
该库非常易于使用,您需要的唯一设置代码是告诉它您的 xcdatamodeld 名称,如果您正在使用 CocoaPods,则还必须导入模块。下面是示例代码
/// If using CocoaPods
import CWCoreData
/// Tell the framework what your xcdatamodeld is called, if you forgot this the framework will raise an exception:
CoreDataStack.defaultStack.dataBaseName = "YOU_DATABASE_NAME"
CoreDataStack.defaultStack.sharedAppGroup = "YOU_SHARED_APP_CONTAINER_DOMAIN"
您应当使用两个上下文。'mainQueueContext' 和 'privateQueueContext'。'mainQueueContext' 应用于使用对象的 UI(例如,使用 fetchedResultsController)添加数据。而 'privateQueueContext' 应用于修改数据(如插入/删除等)。它也是线程安全的,并且应为主要线程访问数据时使用的唯一上下文。'privateQueueContext' 还允许您指定合并策略。以下是一些示例
/// The main context, this is persisted across the app lifecycle:
let mainContext = CoreDataStack.defaultStack.mainQueueContext
/// Get a new private context:
let privateContext = CoreDataStack.privateQueueContext()
/// Get a new private context and specify a merge policy:
let privateContextWithPolicy = CoreDataStack.privateQueueContext(withMergePolicy: .errorMergePolicyType)
保存上下文有两种方法,允许您指定行为或简单地保存。当指定completedHandler时,该块会在数据合并回持久存储协调器之后调用。因此,可以安全地假设数据更改已反映在'mainQueueContext'中。
///Basic save:
CoreDataStack.defaultStack.save(context)
//Advanced save, allowing you to specifiy whether to performAndWait or simply perform:
CoreDataStack.defaultStack.save(context, performAndWait: false, completionHandler: { (result) in
print(result)
})
要将新对象插入数据库 - 假设实体名称为'Event',如示例项目所示。以下示例将向您展示如何在iOS 10及以下版本中执行此操作,如果目标是iOS 10,则可以省略else。
/// Create a new context to use for the insertion, we always use the 'privateQueueContext' to handle database changes. This will merge change back into the persistent store coordinator.
let context = CoreDataStack.privateQueueContext()
/// Create a new var to hold the event object:
var newEvent : Event?
/// If we are running on iOS 10 then we can use the new API to insert:
if #available(iOS 10.0, *) {
newEvent = Event(context: context)
} else {
/// If we are using anything before iOS 10, then we use the helper method from the extension on NSManangedObject
newEvent = Event.insertNewInstance(withContext: context) as? Event
}
/// If appropriate, configure the new managed object.
newEvent?.timestamp = NSDate()
/// We now save the changes, we can specify this with a completion block and whether we want to performBlockAndWait or just perform block:
/// Simply save:
CoreDataStack.defaultStack.save(context)
框架提供了一个NSManangedObject扩展,它添加了一些用于检索对象的帮助方法。以下代码示例展示了如何使用简单谓词检索对象。
do {
/// We use the main context for retrieval if we are going to use the obejct to populate the UI and we are NOT going to make direct changes to the object. Otherwise use the privateQeueContext.
let context = CoreDataStack.defaultStack.mainQueueContext
/// Create the predicate we will use:
let predicate = NSPredicate(format: "timestamp < %@", NSDate())
/// Get the event from the database if one exists with the provided predicate, there are other APIs that do similar operations with more options. See documentation.
let savedEvent = try Event.fetchSingleObject(withPredicate: predicate, context: context, includesPendingChanges: true) as? Event
}
} catch {
print("error")
}
删除对象非常简单
/// Create a new context to use for the deletion, we always use the 'privateQueueContext' to handle database changes. This will merge change back into the persistent store coordinator.
let context = CoreDataStack.privateQueueContext()
let objectToDelete = /// Your Object...
/// Delete the object:
context.delete(objectToDelete)
/// Save the changes, we don't supply a completion handler here:
CoreDataStack.defaultStack.save(context)
使用CWCoreData设置获取结果控制器非常简单。当使用'privateQueueContext'对数据库进行更改时,它会自动更新。
/// Create a var for the fetched results controller:
var fetchedResultsController: NSFetchedResultsController<Event> {
if _fetchedResultsController != nil {
return _fetchedResultsController!
}
/// Create the fetch request:
let fetchRequest: NSFetchRequest<Event> = Event.fetchRequest()
/// Optional: Set the batch size to a suitable number.
fetchRequest.fetchBatchSize = 20
// Edit the sort key as appropriate.
let sortDescriptor = NSSortDescriptor(key: "timestamp", ascending: false)
fetchRequest.sortDescriptors = [sortDescriptor]
/// Edit the section name key path and cache name if appropriate.
/// nil for section name key path means "no sections".
/// We always use the mainQueueContext for FetchedResultsControllers and any other time where we need the UI to be populated from the database object:
let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: CoreDataStack.defaultStack.mainQueueContext, sectionNameKeyPath: nil, cacheName: nil)
aFetchedResultsController.delegate = self
_fetchedResultsController = aFetchedResultsController
do {
try _fetchedResultsController!.performFetch()
} catch {
print(error)
}
return _fetchedResultsController!
}
var _fetchedResultsController: NSFetchedResultsController<Event>? = nil
您现在可以按照您的意愿实现FetchedResultsController的代理。
欢迎提出改进意见和拉取请求。如果发现任何问题,请报告!