ManagedObjectListController demo

This commit is contained in:
John Rommel Estropia
2015-05-06 01:06:22 +09:00
parent d043d64cb1
commit 8d42a4a885
24 changed files with 1566 additions and 453 deletions

View File

@@ -77,7 +77,7 @@ public /*abstract*/ class BaseDataTransaction {
HardcoreData.assert(self.transactionQueue.isCurrentExecutionContext(), "Attempted to delete an entity of type \(typeName(object)) outside its designated queue.")
object.deleteFromContext()
object.inContext(self.context)?.deleteFromContext()
}
// MARK: Saving changes

View File

@@ -34,15 +34,25 @@ public extension DataStack {
// MARK: Public
public func observeObjectList<T: NSManagedObject>(from: From<T>, _ queryClauses: FetchClause...) -> ManagedObjectListController<T> {
public func observeObject<T: NSManagedObject>(object: T) -> ManagedObjectController<T> {
HardcoreData.assert(GCDQueue.Main.isCurrentExecutionContext(), "Attempted to fetch from a \(typeName(self)) outside the main queue.")
HardcoreData.assert(GCDQueue.Main.isCurrentExecutionContext(), "Attempted to observe objects from \(typeName(self)) outside the main queue.")
return ManagedObjectController(
dataStack: self,
object: object
)
}
public func observeObjectList<T: NSManagedObject>(from: From<T>, _ groupBy: GroupBy? = nil, _ queryClauses: FetchClause...) -> ManagedObjectListController<T> {
HardcoreData.assert(GCDQueue.Main.isCurrentExecutionContext(), "Attempted to observe objects from \(typeName(self)) outside the main queue.")
// TODO: sectionNameKeyPath and cacheResults
return ManagedObjectListController(
dataStack: self,
entity: T.self,
sectionNameKeyPath: nil,
sectionNameKeyPath: groupBy?.keyPaths.first,
cacheResults: false,
queryClauses: queryClauses
)

View File

@@ -25,3 +25,279 @@
import Foundation
import CoreData
import GCDKit
private let ManagedObjectListControllerWillChangeListNotification = "ManagedObjectListControllerWillChangeListNotification"
private let ManagedObjectListControllerDidChangeListNotification = "ManagedObjectListControllerDidChangeListNotification"
private let ManagedObjectListControllerDidDeleteObjectNotification = "ManagedObjectListControllerDidDeleteObjectNotification"
private let ManagedObjectListControllerDidUpdateObjectNotification = "ManagedObjectListControllerDidUpdateObjectNotification"
private let UserInfoKeyObject = "UserInfoKeyObject"
private struct NotificationKey {
static var willChangeList: Void?
static var didChangeList: Void?
static var didDeleteObject: Void?
static var didUpdateObject: Void?
}
// MARK: - ManagedObjectController
public final class ManagedObjectController<T: NSManagedObject>: FetchedResultsControllerHandler {
// MARK: Public
public var object: T? {
return self.fetchedResultsController.fetchedObjects?.first as? T
}
public var isObjectDeleted: Bool {
return self.object?.managedObjectContext == nil
}
public func addObserver<U: ManagedObjectObserver where U.EntityType == T>(observer: U) {
HardcoreData.assert(GCDQueue.Main.isCurrentExecutionContext(), "Attempted to add a \(typeName(observer)) outside the main queue.")
self.registerChangeNotification(
&NotificationKey.willChangeList,
name: ManagedObjectListControllerWillChangeListNotification,
toObserver: observer,
callback: { [weak observer, weak self] (objectController) -> Void in
if let observer = observer, let object = self?.object {
observer.managedObjectWillUpdate(objectController, object: object)
}
}
)
self.registerObjectNotification(
&NotificationKey.didDeleteObject,
name: ManagedObjectListControllerDidDeleteObjectNotification,
toObserver: observer,
callback: { [weak observer] (objectController, object) -> Void in
if let observer = observer {
observer.managedObjectWasDeleted(objectController, object: object)
}
}
)
self.registerObjectNotification(
&NotificationKey.didUpdateObject,
name: ManagedObjectListControllerDidUpdateObjectNotification,
toObserver: observer,
callback: { [weak observer] (objectController, object) -> Void in
if let observer = observer {
observer.managedObjectWasUpdated(objectController, object: object)
}
}
)
}
public func removeObserver<U: ManagedObjectObserver where U.EntityType == T>(observer: U) {
HardcoreData.assert(GCDQueue.Main.isCurrentExecutionContext(), "Attempted to remove a \(typeName(observer)) outside the main queue.")
let nilValue: AnyObject? = nil
setAssociatedRetainedObject(nilValue, forKey: &NotificationKey.willChangeList, inObject: observer)
setAssociatedRetainedObject(nilValue, forKey: &NotificationKey.didDeleteObject, inObject: observer)
setAssociatedRetainedObject(nilValue, forKey: &NotificationKey.didUpdateObject, inObject: observer)
}
// MARK: FetchedResultsControllerHandler
private func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
switch type {
case .Delete:
NSNotificationCenter.defaultCenter().postNotificationName(
ManagedObjectListControllerDidDeleteObjectNotification,
object: self,
userInfo: [UserInfoKeyObject: anObject]
)
case .Update:
NSNotificationCenter.defaultCenter().postNotificationName(
ManagedObjectListControllerDidUpdateObjectNotification,
object: self,
userInfo: [UserInfoKeyObject: anObject]
)
default:
break
}
}
private func controllerWillChangeContent(controller: NSFetchedResultsController) {
NSNotificationCenter.defaultCenter().postNotificationName(
ManagedObjectListControllerWillChangeListNotification,
object: self
)
}
private func controllerDidChangeContent(controller: NSFetchedResultsController) {
NSNotificationCenter.defaultCenter().postNotificationName(
ManagedObjectListControllerDidChangeListNotification,
object: self
)
}
// MARK: Internal
internal init(dataStack: DataStack, object: T) {
let context = dataStack.mainContext
let fetchRequest = NSFetchRequest()
fetchRequest.entity = context.entityDescriptionForEntityClass(T.self)
fetchRequest.fetchLimit = 1
fetchRequest.resultType = .ManagedObjectResultType
Where("SELF", isEqualTo: object).applyToFetchRequest(fetchRequest)
SortedBy(.Ascending("objectID")).applyToFetchRequest(fetchRequest)
let fetchedResultsController = NSFetchedResultsController(
fetchRequest: fetchRequest,
managedObjectContext: context,
sectionNameKeyPath: nil,
cacheName: nil
)
let fetchedResultsControllerDelegate = FetchedResultsControllerDelegate()
self.fetchedResultsController = fetchedResultsController
self.fetchedResultsControllerDelegate = fetchedResultsControllerDelegate
self.parentStack = dataStack
fetchedResultsControllerDelegate.handler = self
fetchedResultsControllerDelegate.fetchedResultsController = fetchedResultsController
var error: NSError?
if !fetchedResultsController.performFetch(&error) {
HardcoreData.handleError(
error ?? NSError(hardcoreDataErrorCode: .UnknownError),
"Failed to perform fetch on <\(NSFetchedResultsController.self)>.")
}
}
// MARK: Private
private let fetchedResultsController: NSFetchedResultsController
private let fetchedResultsControllerDelegate: FetchedResultsControllerDelegate
private weak var parentStack: DataStack?
private func registerChangeNotification(notificationKey: UnsafePointer<Void>, name: String, toObserver observer: AnyObject, callback: (objectController: ManagedObjectController<T>) -> Void) {
setAssociatedRetainedObject(
NotificationObserver(
notificationName: name,
object: self,
closure: { [weak self] (note) -> Void in
if let strongSelf = self {
callback(objectController: strongSelf)
}
}
),
forKey: notificationKey,
inObject: observer
)
}
private func registerObjectNotification(notificationKey: UnsafePointer<Void>, name: String, toObserver observer: AnyObject, callback: (objectController: ManagedObjectController<T>, object: T) -> Void) {
setAssociatedRetainedObject(
NotificationObserver(
notificationName: name,
object: self,
closure: { [weak self] (note) -> Void in
if let strongSelf = self,
let userInfo = note.userInfo,
let object = userInfo[UserInfoKeyObject] as? T {
callback(
objectController: strongSelf,
object: object
)
}
}
),
forKey: notificationKey,
inObject: observer
)
}
}
// MARK: - FetchedResultsControllerHandler
private protocol FetchedResultsControllerHandler: class {
func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?)
func controllerWillChangeContent(controller: NSFetchedResultsController)
func controllerDidChangeContent(controller: NSFetchedResultsController)
}
// MARK: - FetchedResultsControllerDelegate
private final class FetchedResultsControllerDelegate: NSFetchedResultsControllerDelegate {
// MARK: NSFetchedResultsControllerDelegate
@objc func controllerWillChangeContent(controller: NSFetchedResultsController) {
self.handler?.controllerWillChangeContent(controller)
}
@objc func controllerDidChangeContent(controller: NSFetchedResultsController) {
self.handler?.controllerDidChangeContent(controller)
}
@objc func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
self.handler?.controller(controller, didChangeObject: anObject, atIndexPath: indexPath, forChangeType: type, newIndexPath: newIndexPath)
}
// MARK: Private
weak var handler: FetchedResultsControllerHandler?
weak var fetchedResultsController: NSFetchedResultsController? {
didSet {
oldValue?.delegate = nil
self.fetchedResultsController?.delegate = self
}
}
deinit {
self.fetchedResultsController?.delegate = nil
}
}

View File

@@ -30,25 +30,37 @@ import GCDKit
private let ManagedObjectListControllerWillChangeListNotification = "ManagedObjectListControllerWillChangeListNotification"
private let ManagedObjectListControllerDidChangeListNotification = "ManagedObjectListControllerDidChangeListNotification"
private let ManagedObjectListControllerDidInsertObjectNotification = "ManagedObjectListControllerDidInsertObjectNotification"
private let ManagedObjectListControllerDidDeleteObjectNotification = "ManagedObjectListControllerDidDeleteObjectNotification"
private let ManagedObjectListControllerDidUpdateObjectNotification = "ManagedObjectListControllerDidUpdateObjectNotification"
private let ManagedObjectListControllerDidMoveObjectNotification = "ManagedObjectListControllerDidMoveObjectNotification"
private let ManagedObjectListControllerDidInsertSectionNotification = "ManagedObjectListControllerDidInsertSectionNotification"
private let ManagedObjectListControllerDidDeleteSectionNotification = "ManagedObjectListControllerDidDeleteSectionNotification"
private let UserInfoKeyObject = "UserInfoKeyObject"
private let UserInfoKeyIndexPath = "UserInfoKeyIndexPath"
private let UserInfoKeyNewIndexPath = "UserInfoKeyNewIndexPath"
private let UserInfoKeySectionInfo = "UserInfoKeySectionInfo"
private let UserInfoKeySectionIndex = "UserInfoKeySectionIndex"
private struct NotificationKey {
static var willChangeList: Void?
static var didChangeList: Void?
static var didInsertObject: Void?
static var didDeleteObject: Void?
static var didUpdateObject: Void?
static var didMoveObject: Void?
static var didInsertSection: Void?
static var didDeleteSection: Void?
}
// MARK: - ManagedObjectListController
public final class ManagedObjectListController<T: NSManagedObject>: FetchedResultsControllerHandler {
@@ -65,153 +77,289 @@ public final class ManagedObjectListController<T: NSManagedObject>: FetchedResul
return self.fetchedResultsController.sections?.count ?? 0
}
public func numberOfItemsInSection(section: Int) -> Int {
public func numberOfObjectsInSection(section: Int) -> Int {
return (self.fetchedResultsController.sections?[section] as? NSFetchedResultsSectionInfo)?.numberOfObjects ?? 0
}
public func addObserver<U: ManagedObjectListObserver where U.EntityType == T>(observer: U) {
public func sectionInfoAtIndex(section: Int) -> NSFetchedResultsSectionInfo {
return self.fetchedResultsController.sections![section] as! NSFetchedResultsSectionInfo
}
public func addObserver<U: ManagedObjectListChangeObserver where U.EntityType == T>(observer: U) {
HardcoreData.assert(GCDQueue.Main.isCurrentExecutionContext(), "Attempted to add a \(typeName(observer)) outside the main queue.")
setAssociatedRetainedObject(
NotificationObserver(
notificationName: ManagedObjectListControllerWillChangeListNotification,
object: self,
closure: { [weak self, weak observer] (note) -> Void in
self.registerChangeNotification(
&NotificationKey.willChangeList,
name: ManagedObjectListControllerWillChangeListNotification,
toObserver: observer,
callback: { [weak observer] (listController) -> Void in
if let observer = observer {
if let strongSelf = self, let strongObserver = observer {
strongObserver.managedObjectListWillChange(strongSelf)
}
observer.managedObjectListWillChange(listController)
}
),
forKey: &NotificationKey.willChangeList,
inObject: observer
}
)
setAssociatedRetainedObject(
NotificationObserver(
notificationName: ManagedObjectListControllerDidChangeListNotification,
object: self,
closure: { [weak self, weak observer] (note) -> Void in
self.registerChangeNotification(
&NotificationKey.didChangeList,
name: ManagedObjectListControllerDidChangeListNotification,
toObserver: observer,
callback: { [weak observer] (listController) -> Void in
if let observer = observer {
if let strongSelf = self, let strongObserver = observer {
strongObserver.managedObjectListDidChange(strongSelf)
}
observer.managedObjectListDidChange(listController)
}
),
forKey: &NotificationKey.willChangeList,
inObject: observer
)
setAssociatedRetainedObject(
NotificationObserver(
notificationName: ManagedObjectListControllerDidInsertObjectNotification,
object: self,
closure: { [weak self, weak observer] (note) -> Void in
if let strongSelf = self,
let strongObserver = observer,
let userInfo = note.userInfo,
let object = userInfo[UserInfoKeyObject] as? T,
let newIndexPath = userInfo[UserInfoKeyNewIndexPath] as? NSIndexPath {
strongObserver.managedObjectList(
strongSelf,
didInsertObject: object,
toIndexPath: newIndexPath
)
}
}
),
forKey: &NotificationKey.didInsertObject,
inObject: observer
)
setAssociatedRetainedObject(
NotificationObserver(
notificationName: ManagedObjectListControllerDidDeleteObjectNotification,
object: self,
closure: { [weak self, weak observer] (note) -> Void in
if let strongSelf = self,
let strongObserver = observer,
let userInfo = note.userInfo,
let object = userInfo[UserInfoKeyObject] as? T,
let indexPath = userInfo[UserInfoKeyIndexPath] as? NSIndexPath {
strongObserver.managedObjectList(
strongSelf,
didDeleteObject: object,
fromIndexPath: indexPath
)
}
}
),
forKey: &NotificationKey.didDeleteObject,
inObject: observer
)
setAssociatedRetainedObject(
NotificationObserver(
notificationName: ManagedObjectListControllerDidUpdateObjectNotification,
object: self,
closure: { [weak self, weak observer] (note) -> Void in
if let strongSelf = self,
let strongObserver = observer,
let userInfo = note.userInfo,
let object = userInfo[UserInfoKeyObject] as? T,
let indexPath = userInfo[UserInfoKeyIndexPath] as? NSIndexPath {
strongObserver.managedObjectList(
strongSelf,
didUpdateObject: object,
atIndexPath: indexPath
)
}
}
),
forKey: &NotificationKey.didUpdateObject,
inObject: observer
)
setAssociatedRetainedObject(
NotificationObserver(
notificationName: ManagedObjectListControllerDidMoveObjectNotification,
object: self,
closure: { [weak self, weak observer] (note) -> Void in
if let strongSelf = self,
let strongObserver = observer,
let userInfo = note.userInfo,
let object = userInfo[UserInfoKeyObject] as? T,
let indexPath = userInfo[UserInfoKeyIndexPath] as? NSIndexPath ,
let newIndexPath = userInfo[UserInfoKeyNewIndexPath] as? NSIndexPath {
strongObserver.managedObjectList(
strongSelf,
didMoveObject: object,
fromIndexPath: indexPath,
toIndexPath: newIndexPath
)
}
}
),
forKey: &NotificationKey.didMoveObject,
inObject: observer
}
)
}
public func removeObserver<U: ManagedObjectListObserver where U.EntityType == T>(observer: U) {
public func addObserver<U: ManagedObjectListObjectObserver where U.EntityType == T>(observer: U) {
HardcoreData.assert(GCDQueue.Main.isCurrentExecutionContext(), "Attempted to add a \(typeName(observer)) outside the main queue.")
self.registerChangeNotification(
&NotificationKey.willChangeList,
name: ManagedObjectListControllerWillChangeListNotification,
toObserver: observer,
callback: { [weak observer] (listController) -> Void in
if let observer = observer {
observer.managedObjectListWillChange(listController)
}
}
)
self.registerChangeNotification(
&NotificationKey.didChangeList,
name: ManagedObjectListControllerDidChangeListNotification,
toObserver: observer,
callback: { [weak observer] (listController) -> Void in
if let observer = observer {
observer.managedObjectListDidChange(listController)
}
}
)
self.registerObjectNotification(
&NotificationKey.didInsertObject,
name: ManagedObjectListControllerDidInsertObjectNotification,
toObserver: observer,
callback: { [weak observer] (listController, object, indexPath, newIndexPath) -> Void in
if let observer = observer {
observer.managedObjectList(
listController,
didInsertObject: object,
toIndexPath: newIndexPath!
)
}
}
)
self.registerObjectNotification(
&NotificationKey.didDeleteObject,
name: ManagedObjectListControllerDidDeleteObjectNotification,
toObserver: observer,
callback: { [weak observer] (listController, object, indexPath, newIndexPath) -> Void in
if let observer = observer {
observer.managedObjectList(
listController,
didDeleteObject: object,
fromIndexPath: indexPath!
)
}
}
)
self.registerObjectNotification(
&NotificationKey.didUpdateObject,
name: ManagedObjectListControllerDidUpdateObjectNotification,
toObserver: observer,
callback: { [weak observer] (listController, object, indexPath, newIndexPath) -> Void in
if let observer = observer {
observer.managedObjectList(
listController,
didUpdateObject: object,
atIndexPath: indexPath!
)
}
}
)
self.registerObjectNotification(
&NotificationKey.didMoveObject,
name: ManagedObjectListControllerDidMoveObjectNotification,
toObserver: observer,
callback: { [weak observer] (listController, object, indexPath, newIndexPath) -> Void in
if let observer = observer {
observer.managedObjectList(
listController,
didMoveObject: object,
fromIndexPath: indexPath!,
toIndexPath: newIndexPath!
)
}
}
)
}
public func addObserver<U: ManagedObjectListSectionObserver where U.EntityType == T>(observer: U) {
HardcoreData.assert(GCDQueue.Main.isCurrentExecutionContext(), "Attempted to add a \(typeName(observer)) outside the main queue.")
self.registerChangeNotification(
&NotificationKey.willChangeList,
name: ManagedObjectListControllerWillChangeListNotification,
toObserver: observer,
callback: { [weak observer] (listController) -> Void in
if let observer = observer {
observer.managedObjectListWillChange(listController)
}
}
)
self.registerChangeNotification(
&NotificationKey.didChangeList,
name: ManagedObjectListControllerDidChangeListNotification,
toObserver: observer,
callback: { [weak observer] (listController) -> Void in
if let observer = observer {
observer.managedObjectListDidChange(listController)
}
}
)
self.registerObjectNotification(
&NotificationKey.didInsertObject,
name: ManagedObjectListControllerDidInsertObjectNotification,
toObserver: observer,
callback: { [weak observer] (listController, object, indexPath, newIndexPath) -> Void in
if let observer = observer {
observer.managedObjectList(
listController,
didInsertObject: object,
toIndexPath: newIndexPath!
)
}
}
)
self.registerObjectNotification(
&NotificationKey.didDeleteObject,
name: ManagedObjectListControllerDidDeleteObjectNotification,
toObserver: observer,
callback: { [weak observer] (listController, object, indexPath, newIndexPath) -> Void in
if let observer = observer {
observer.managedObjectList(
listController,
didDeleteObject: object,
fromIndexPath: indexPath!
)
}
}
)
self.registerObjectNotification(
&NotificationKey.didUpdateObject,
name: ManagedObjectListControllerDidUpdateObjectNotification,
toObserver: observer,
callback: { [weak observer] (listController, object, indexPath, newIndexPath) -> Void in
if let observer = observer {
observer.managedObjectList(
listController,
didUpdateObject: object,
atIndexPath: indexPath!
)
}
}
)
self.registerObjectNotification(
&NotificationKey.didMoveObject,
name: ManagedObjectListControllerDidMoveObjectNotification,
toObserver: observer,
callback: { [weak observer] (listController, object, indexPath, newIndexPath) -> Void in
if let observer = observer {
observer.managedObjectList(
listController,
didMoveObject: object,
fromIndexPath: indexPath!,
toIndexPath: newIndexPath!
)
}
}
)
self.registerSectionNotification(
&NotificationKey.didInsertSection,
name: ManagedObjectListControllerDidInsertSectionNotification,
toObserver: observer,
callback: { [weak observer] (listController, sectionInfo, sectionIndex) -> Void in
if let observer = observer {
observer.managedObjectList(
listController,
didInsertSection: sectionInfo,
toSectionIndex: sectionIndex
)
}
}
)
self.registerSectionNotification(
&NotificationKey.didDeleteSection,
name: ManagedObjectListControllerDidDeleteSectionNotification,
toObserver: observer,
callback: { [weak observer] (listController, sectionInfo, sectionIndex) -> Void in
if let observer = observer {
observer.managedObjectList(
listController,
didDeleteSection: sectionInfo,
fromSectionIndex: sectionIndex
)
}
}
)
}
public func removeObserver<U: ManagedObjectListChangeObserver where U.EntityType == T>(observer: U) {
HardcoreData.assert(GCDQueue.Main.isCurrentExecutionContext(), "Attempted to remove a \(typeName(observer)) outside the main queue.")
setAssociatedRetainedObject(nil as AnyObject?, forKey: &NotificationKey.willChangeList, inObject: observer)
setAssociatedRetainedObject(nil as AnyObject?, forKey: &NotificationKey.didChangeList, inObject: observer)
setAssociatedRetainedObject(nil as AnyObject?, forKey: &NotificationKey.didInsertObject, inObject: observer)
setAssociatedRetainedObject(nil as AnyObject?, forKey: &NotificationKey.didDeleteObject, inObject: observer)
setAssociatedRetainedObject(nil as AnyObject?, forKey: &NotificationKey.didUpdateObject, inObject: observer)
setAssociatedRetainedObject(nil as AnyObject?, forKey: &NotificationKey.didMoveObject, inObject: observer)
let nilValue: AnyObject? = nil
setAssociatedRetainedObject(nilValue, forKey: &NotificationKey.willChangeList, inObject: observer)
setAssociatedRetainedObject(nilValue, forKey: &NotificationKey.didChangeList, inObject: observer)
setAssociatedRetainedObject(nilValue, forKey: &NotificationKey.didInsertObject, inObject: observer)
setAssociatedRetainedObject(nilValue, forKey: &NotificationKey.didDeleteObject, inObject: observer)
setAssociatedRetainedObject(nilValue, forKey: &NotificationKey.didUpdateObject, inObject: observer)
setAssociatedRetainedObject(nilValue, forKey: &NotificationKey.didMoveObject, inObject: observer)
setAssociatedRetainedObject(nilValue, forKey: &NotificationKey.didInsertSection, inObject: observer)
setAssociatedRetainedObject(nilValue, forKey: &NotificationKey.didDeleteSection, inObject: observer)
}
// MARK: FetchedResultsControllerHandler
private func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
@@ -263,6 +411,31 @@ public final class ManagedObjectListController<T: NSManagedObject>: FetchedResul
private func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
switch type {
case .Insert:
NSNotificationCenter.defaultCenter().postNotificationName(
ManagedObjectListControllerDidInsertSectionNotification,
object: self,
userInfo: [
UserInfoKeySectionInfo: sectionInfo,
UserInfoKeySectionIndex: NSNumber(integer: sectionIndex)
]
)
case .Delete:
NSNotificationCenter.defaultCenter().postNotificationName(
ManagedObjectListControllerDidDeleteSectionNotification,
object: self,
userInfo: [
UserInfoKeySectionInfo: sectionInfo,
UserInfoKeySectionIndex: NSNumber(integer: sectionIndex)
]
)
default:
break
}
}
private func controllerWillChangeContent(controller: NSFetchedResultsController) {
@@ -336,6 +509,77 @@ public final class ManagedObjectListController<T: NSManagedObject>: FetchedResul
private let fetchedResultsController: NSFetchedResultsController
private let fetchedResultsControllerDelegate: FetchedResultsControllerDelegate
private weak var parentStack: DataStack?
private func registerChangeNotification(notificationKey: UnsafePointer<Void>, name: String, toObserver observer: AnyObject, callback: (listController: ManagedObjectListController<T>) -> Void) {
setAssociatedRetainedObject(
NotificationObserver(
notificationName: name,
object: self,
closure: { [weak self] (note) -> Void in
if let strongSelf = self {
callback(listController: strongSelf)
}
}
),
forKey: notificationKey,
inObject: observer
)
}
private func registerObjectNotification(notificationKey: UnsafePointer<Void>, name: String, toObserver observer: AnyObject, callback: (listController: ManagedObjectListController<T>, object: T, indexPath: NSIndexPath?, newIndexPath: NSIndexPath?) -> Void) {
setAssociatedRetainedObject(
NotificationObserver(
notificationName: name,
object: self,
closure: { [weak self] (note) -> Void in
if let strongSelf = self,
let userInfo = note.userInfo,
let object = userInfo[UserInfoKeyObject] as? T {
callback(
listController: strongSelf,
object: object,
indexPath: userInfo[UserInfoKeyIndexPath] as? NSIndexPath,
newIndexPath: userInfo[UserInfoKeyNewIndexPath] as? NSIndexPath
)
}
}
),
forKey: notificationKey,
inObject: observer
)
}
private func registerSectionNotification(notificationKey: UnsafePointer<Void>, name: String, toObserver observer: AnyObject, callback: (listController: ManagedObjectListController<T>, sectionInfo: NSFetchedResultsSectionInfo, sectionIndex: Int) -> Void) {
setAssociatedRetainedObject(
NotificationObserver(
notificationName: name,
object: self,
closure: { [weak self] (note) -> Void in
if let strongSelf = self,
let userInfo = note.userInfo,
let sectionInfo = userInfo[UserInfoKeySectionInfo] as? NSFetchedResultsSectionInfo,
let sectionIndex = (userInfo[UserInfoKeySectionIndex] as? NSNumber)?.integerValue {
callback(
listController: strongSelf,
sectionInfo: sectionInfo,
sectionIndex: sectionIndex
)
}
}
),
forKey: notificationKey,
inObject: observer
)
}
}
@@ -361,16 +605,6 @@ private final class FetchedResultsControllerDelegate: NSFetchedResultsController
// MARK: NSFetchedResultsControllerDelegate
@objc func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
self.handler?.controller(controller, didChangeObject: anObject, atIndexPath: indexPath, forChangeType: type, newIndexPath: newIndexPath)
}
@objc func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
self.handler?.controller(controller, didChangeSection: sectionInfo, atIndex: sectionIndex, forChangeType: type)
}
@objc func controllerWillChangeContent(controller: NSFetchedResultsController) {
self.handler?.controllerWillChangeContent(controller)
@@ -381,6 +615,16 @@ private final class FetchedResultsControllerDelegate: NSFetchedResultsController
self.handler?.controllerDidChangeContent(controller)
}
@objc func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
self.handler?.controller(controller, didChangeObject: anObject, atIndexPath: indexPath, forChangeType: type, newIndexPath: newIndexPath)
}
@objc func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
self.handler?.controller(controller, didChangeSection: sectionInfo, atIndex: sectionIndex, forChangeType: type)
}
@objc func controller(controller: NSFetchedResultsController, sectionIndexTitleForSectionName sectionName: String?) -> String? {
return self.handler?.controller(controller, sectionIndexTitleForSectionName: sectionName)

View File

@@ -27,23 +27,21 @@ import Foundation
import CoreData
// MARK: - ManagedObjectListObserver
// MARK: - ManagedObjectListChangeObserver
public protocol ManagedObjectListObserver: class {
public protocol ManagedObjectListChangeObserver: class {
typealias EntityType: NSManagedObject
func managedObjectListWillChange(listController: ManagedObjectListController<EntityType>)
// func managedObjectList(listController: ManagedObjectListController<EntityType>, didInsertSection sectionInfo: NSFetchedResultsSectionInfo, toSectionIndex sectionIndex: Int)
//
// func managedObjectList(listController: ManagedObjectListController<EntityType>, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int)
//
// func managedObjectList(listController: ManagedObjectListController<EntityType>, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int)
//
// func managedObjectList(listController: ManagedObjectListController<EntityType>, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int)
func managedObjectListDidChange(listController: ManagedObjectListController<EntityType>)
}
// MARK: - ManagedObjectListObjectObserver
public protocol ManagedObjectListObjectObserver: ManagedObjectListChangeObserver {
func managedObjectList(listController: ManagedObjectListController<EntityType>, didInsertObject object: EntityType, toIndexPath indexPath: NSIndexPath)
@@ -54,11 +52,19 @@ public protocol ManagedObjectListObserver: class {
func managedObjectList(listController: ManagedObjectListController<EntityType>, didMoveObject object: EntityType, fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath)
func managedObjectListDidChange(listController: ManagedObjectListController<EntityType>)
//
// private func controller(controller: NSFetchedResultsController, sectionIndexTitleForSectionName sectionName: String?) -> String? {
//
// return nil
// }
}
// MARK: - ManagedObjectListSectionObserver
public protocol ManagedObjectListSectionObserver: ManagedObjectListObjectObserver {
func managedObjectList(listController: ManagedObjectListController<EntityType>, didInsertSection sectionInfo: NSFetchedResultsSectionInfo, toSectionIndex sectionIndex: Int)
func managedObjectList(listController: ManagedObjectListController<EntityType>, didDeleteSection sectionInfo: NSFetchedResultsSectionInfo, fromSectionIndex sectionIndex: Int)
}

View File

@@ -1,13 +0,0 @@
//
// ManagedObjectListSectionInfo.swift
// HardcoreData
//
// Created by John Rommel Estropia on 2015/03/11.
// Copyright (c) 2015 John Rommel Estropia. All rights reserved.
//
import UIKit
class ManagedObjectListSectionInfo: NSObject {
}

View File

@@ -0,0 +1,41 @@
//
// ManagedObjectObserver.swift
// HardcoreData
//
// Copyright (c) 2015 John Rommel Estropia
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import CoreData
// MARK: - ManagedObjectObserver
public protocol ManagedObjectObserver: class {
typealias EntityType: NSManagedObject
func managedObjectWillUpdate(objectController: ManagedObjectController<EntityType>, object: EntityType)
func managedObjectWasUpdated(objectController: ManagedObjectController<EntityType>, object: EntityType)
func managedObjectWasDeleted(objectController: ManagedObjectController<EntityType>, object: EntityType)
}

101
HardcoreData/README.md Normal file
View File

@@ -0,0 +1,101 @@
# HardcoreData
[![Version](https://img.shields.io/cocoapods/v/HardcoreData.svg?style=flat)](http://cocoadocs.org/docsets/HardcoreData)
[![Platform](https://img.shields.io/cocoapods/p/HardcoreData.svg?style=flat)](http://cocoadocs.org/docsets/HardcoreData)
[![License](https://img.shields.io/cocoapods/l/HardcoreData.svg?style=flat)](http://cocoadocs.org/docsets/HardcoreData)
Simple, elegant, and smart Core Data programming with Swift
## Features
- Supports multiple persistent stores per *data stack*, just the way .xcdatamodeld files are supposed to. HardcoreData will also manage one *data stack* by default, but you can create and manage as many as you need. (see "Setting up")
- Ability to plug-in your own logging framework (or your favorite 3rd-party logger). (see "Logging and error handling")
- Makes it hard to fall into common concurrency mistakes. All Core Data tasks are encapsulated into safer, higher-level abstractions without sacrificing flexibility and customizability. (see "Saving and processing transactions")
- Provides convenient API for common use cases. (see "Fetching and querying")
- Pleasant API designed around Swifts code elegance and type safety. (see "TL;DR sample codes")
#### TL;DR sample codes
Quick-setup:
```swift
HardcoreData.defaultStack.addSQLiteStore("MyStore.sqlite")
```
Simple transactions:
```swift
HardcoreData.beginAsynchronous { (transaction) -> Void in
let object = transaction.create(MyEntity)
object.entityID = 1
object.name = "test entity"
transaction.commit { (result) -> Void in
switch result {
case .Success(let hasChanges): println("success!")
case .Failure(let error): println(error)
}
}
}
```
Easy fetching:
```swift
let objects = HardcoreData.fetchAll(From(MyEntity))
```
```swift
let objects = HardcoreData.fetchAll(
From(MyEntity),
Where("entityID", isEqualTo: 1),
SortedBy(.Ascending("entityID"), .Descending("name")),
CustomizeFetch { (fetchRequest) -> Void in
fetchRequest.includesPendingChanges = true
}
)
```
Simple queries:
```swift
let count = HardcoreData.queryValue(
From(MyEntity),
Select<Int>(.Count("entityID"))
)
```
## Architecture
For maximum safety and performance, HardcoreData will enforce coding patterns and practices it was designed for. (Don't worry, it's not as scary as it sounds.) But it is advisable to understand the "magic" of HardcoreData before you use it in your apps.
If you are already familiar with the inner workings of CoreData, here is a mapping of `HardcoreData` abstractions:
| *Core Data* | *HardcoreData* |
| --- | --- |
| `NSManagedObjectModel` / `NSPersistentStoreCoordinator`<br />(.xcdatamodeld file) | `DataStack` |
| `NSPersistentStore`<br />("Configuration"s in the .xcdatamodeld file) | `DataStack` configuration<br />(multiple sqlite / in-memory stores per stack) |
| `NSManagedObjectContext` | `BaseDataTransaction` subclasses<br />(`SynchronousDataTransaction`, `AsynchronousDataTransaction`, `DetachedDataTransaction`) |
RestKit and MagicalRecord set up their `NSManagedObjectContext`s this way:
<img src="https://cloud.githubusercontent.com/assets/3029684/6734049/40579660-ce99-11e4-9d38-829877386afb.png" alt="nested contexts" height=271 />
This ensures maximum data integrity between contexts without blocking the main queue. But as <a href="http://floriankugler.com/2013/04/29/concurrent-core-data-stack-performance-shootout/">Florian Kugler's investigation</a> found out, merging contexts is still by far faster than saving nested contexts. HardcoreData's `DataStack` takes the best of both worlds by treating the main `NSManagedObjectContext` as a read-only context, and only allows changes to be made within *transactions*:
<img src="https://cloud.githubusercontent.com/assets/3029684/6734050/4078b642-ce99-11e4-95ea-c0c1d24fbe80.png" alt="nested contexts and merge hybrid" height=212 />
This allows for a butter-smooth main thread, while still taking advantage of safe nested contexts.
## Setting up
## Saving and processing transactions
## Fetching and querying
## Logging and error handling
## Observing changes and notifications (currently in the works)