motion/cdq/context.rb in cdq-0.1.9 vs motion/cdq/context.rb in cdq-0.1.10
- old
+ new
@@ -1,15 +1,20 @@
-
module CDQ
class CDQContextManager
BACKGROUND_SAVE_NOTIFICATION = 'com.infinitered.cdq.context.background_save_completed'
+ DID_FINISH_IMPORT_NOTIFICATION = 'com.infinitered.cdq.context.did_finish_import'
def initialize(opts = {})
@store_manager = opts[:store_manager]
end
+
+ def dealloc
+ NSNotificationCenter.defaultCenter.removeObserver(self) if @observed_context
+ super
+ end
# Push a new context onto the stack for the current thread, making that context the
# default. If a block is supplied, push for the duration of the block and then
# return to the previous state.
#
@@ -64,26 +69,36 @@
# will be set to the previous head context. If a block is supplied, the new context
# will exist for the duration of the block and then the previous state will be restore_managerd.
#
def new(concurrency_type, &block)
@has_been_set_up = true
+
context = NSManagedObjectContext.alloc.initWithConcurrencyType(concurrency_type)
if current
context.parentContext = current
else
if @store_manager.invalid?
raise "store coordinator not found. Cannot create the first context without one."
else
- context.persistentStoreCoordinator = @store_manager.current
+ context.mergePolicy = NSMergePolicy.alloc.initWithMergeType(NSMergeByPropertyObjectTrumpMergePolicyType)
+ context.performBlockAndWait ->{
+ coordinator = @store_manager.current
+ context.persistentStoreCoordinator = coordinator
+ #Dispatch::Queue.main.async {
+ NSNotificationCenter.defaultCenter.addObserver(self, selector:"did_finish_import:", name:NSPersistentStoreDidImportUbiquitousContentChangesNotification, object:nil)
+ @observed_context = context
+ #}
+ }
end
end
push(context, &block)
end
# Save all contexts in the stack, starting with the current and working down.
#
def save(options = {})
+ set_timestamps
always_wait = options[:always_wait]
stack.reverse.each do |context|
if always_wait || context.concurrencyType == NSMainQueueConcurrencyType
context.performBlockAndWait( -> {
@@ -123,11 +138,20 @@
end
end
end
true
end
+
+ def did_finish_import(notification)
+ @observed_context.performBlockAndWait ->{
+ @observed_context.mergeChangesFromContextDidSaveNotification(notification)
+ NSNotificationCenter.defaultCenter.postNotificationName(DID_FINISH_IMPORT_NOTIFICATION, object:self, userInfo:{context: @observed_context})
+ }
+ end
+
+
private
def push_to_stack(value)
lstack = stack
lstack << value
@@ -187,9 +211,18 @@
puts indent + "#{key}: #{value}"
end
end
end
end
+
+ def set_timestamps
+ now = Time.now
+ eos = current.insertedObjects.allObjects + current.updatedObjects.allObjects
+ eos.each do |e|
+ e.created_at ||= now if e.respond_to? :created_at=
+ e.updated_at = now if e.respond_to? :updated_at=
+ end
+ end
-end
+ end
end