我在执行获取请求并更新 4 个属性的线程中有第二个 MOC。在主线程中,我注册了 NSManagedObjectDidSaveNotification 处理程序,该处理程序合并了我的第二个 MOC 的更改。如果我在这个方法中设置一个断点并检查更新的对象,那么我确实会看到新的属性。但是,如果我在数组中添加对象 ID 并在合并 + 保存后借助它们的 ID 访问相同的对象,那么我会得到旧属性。
令人惊讶的是,我观察到在 2 个属性中,一个属性具有新价值,而另一个没有。这令人难以置信,经过几个小时的调试,我无法理解这背后的原因。如果天才们对这个问题有所了解,那将会很有帮助。
更新
在我的主线程中:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(contextDidSave:)
name:NSManagedObjectContextDidSaveNotification
object:nil];
- (NSManagedObjectContext *)mainThreadObjectContext
{
if (myMainThreadObjectContext == nil) {
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
myMainThreadObjectContext = [[NSManagedObjectContext alloc] init];
[myStateManagedObjectContext setPersistentStoreCoordinator:coordinator];
[myStateManagedObjectContext setMergePolicy:NSMergeByPropertyStoreTrumpMergePolicy];
[myStateManagedObjectContext setRetainsRegisteredObjects:NO];
[myStateManagedObjectContext setUndoManager:nil];
}
}
return myMainThreadObjectContext;
}
我在这个方法中合并了在线程 MOC 中所做的更改
- (void) contextDidSave:(NSNotification *)notification
{
if (![NSThread isMainThread])
{
[self performSelectorOnMainThread:@selector(contextDidSave:) withObject:notification waitUntilDone:NO];
return;
}
NSManagedObjectContext *moc = [notification object];
NSMutableSet *updatedObjects = [NSMutableSet set];
if (![moc isEqual:self.mainThreadManagedObjectContext] && [[moc persistentStoreCoordinator] isEqual:self.persistentStoreCoordinator])
{
@synchronized(self)
{
NSDictionary *userinfoDict = [notification userInfo];
NSSet *insertedObjectSet = [userinfoDict valueForKeyPath:@"inserted.objectID"];
NSSet *updatedObjectSet = [userinfoDict valueForKeyPath:@"updated.objectID"];
[updatedObjects addObjectsFromArray:insertedObjectSet.allObjects];
[updatedObjects addObjectsFromArray:updatedObjectSet.allObjects];
@try {
[self.mainThreadManagedObjectContext mergeChangesFromContextDidSaveNotification:notification];
}
@catch (NSException * e) {
NSLog(@"Exception %@ when mergning contexts in -[%@ %@]", e, NSStringFromClass(self.class), NSStringFromSelector(_cmd));
}
if(updatedObjects.count>0)
{
[self performSelector:@selector(updatedStatus:) withObject:updatedObjects afterDelay:0.5];
}
NSError *saveError = nil;
if (![self.mainThreadManagedObjectContext save:&saveError])
{
NSLog(@"Could not save objects in -[%@ %@]. Error = %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), saveError);
}
}
}
}
在主线程中,我有从 MOC 获取现有对象并更新从服务器接收到的属性的方法。但是,在我的辅助线程中,我有插入新托管对象和稍后更新属性的方法,这些属性需要很长时间才能在主线程中处理
在第二个线程中,我有以下代码
-(void) startTaskThread
{
thread_ = [[NSThread alloc] initWithTarget:self selector:@selector(executeTask)
object:nil];
[thread_ start];
}
-(void) executeTask
{
@synchronized(self)
{
[self saveContext];
NSLog(@"\n\nStarting Task thread [%@]!!!!\n\n", self);
for(;;)
{
if([[NSThread currentThread] isCancelled])
break;
@autoreleasepool
{
[condition_ lock];
if(taskArray_.count==0)
{
[condition_ wait];
}
[condition_ unlock];
@try {
if(taskArray_.count>0)
{
NSInvocation *invocation = [self.taskArray objectAtIndex:0];
if([[NSThread currentThread] isCancelled])
break;
else if(!([[NSThread currentThread] isCancelled]) && [self
respondsToSelector:invocation.selector ])
{
[invocation invokeWithTarget:self];
[self.taskArray removeObjectAtIndex:0];
}
}
}
@catch (NSException *exception) {
NSLog(@"Exception %@", exception.debugDescription);
}
@finally {
}
}
}
}
// Save Moc.
if([[[self managedObjectContext] insertedObjects] count]>0 || ([[[self
managedObjectContext] updatedObjects] count]>0) )
{
NSError *error = nil;
if(![[self managedObjectContext] save:&error])
{
NSLog(@"Moc Save Error %@", [error localizedDescription]);
}
}
[self.managedObjectContext reset];
}
我的辅助线程中的 saveContext 方法如下:
-(void) saveContext
{
if(!thread_ || [thread_ isCancelled])
{
// Clean up cache here //
return;
}
_/* --- Here i have code that iterates through the properties that were received from the network and stored in a cache of NSDictionary data type */_
// Now i save the threaded MOC.
if([[[self managedObjectContext] insertedObjects] count]>0 || ([[[self managedObjectContext] updatedObjects] count]>0) )
{
NSError *error = nil;
NSLog(@"We are merging the changes now.. [%d], [%d]", [[[self managedObjectContext] insertedObjects] count], [[[self managedObjectContext] updatedObjects] count]);
if(![[self managedObjectContext] save:&error])
{
NSLog(@"Moc Save Error %@", [error localizedDescription]);
}
}
_// I create a dispatch queue here to repeteadly call this method. This serves as a hear-beat dispatch queue that checks for updated/inserted objects every 5 seconds._
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_queue_t queue = dispatch_queue_create("com.myCompany.mocSaveQ", 0);
dispatch_after(popTime, queue, ^(void)
{
// Save Moc.
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(saveContext)]];
invocation.selector = @selector(saveContext);
invocation.target = self;
[self addTask:invocation];
});
dispatch_release(queue);
}
现在,在调试器中,我尝试在线程/第二个 MOC 上调用 [NSManagedObjectContext save] 之前在线程中打印更新的对象,并且我确实看到了应用于该托管对象的相应属性的更改。但是,当我尝试在我的主线程中为 contextDidSave: 方法中的更新对象打印通知对象的 userInfo 字典时,尽管它列出了相同的对象,但只有一个在线程中更新的属性没有新值。这让我很困惑。
更新 2
这里有更多代码可以帮助更好地理解它。
在我的主线程中
数据字典是一个包含属性和子字典的 NSDictionary
-(void) processData:(NSDictionary*) data
{
for(NSString *key in data)
{
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
fetchRequest.entity = [NSEntityDescription entityForName:@"MyEntity" inManagedObjectContext:self.managedObjectContext];
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"lookupKey = %@", key];
NSArray *fetchResults = nil;
NSError *error = nil;
@synchronized(@"fetch_request_for_lookupKey")
{
@try
{
fetchResults = [moc executeFetchRequest:fetchRequest error:&error];
}
@catch (NSException *exception)
{
NSLog(@"Exception %@ when executing fetch %@", exception, NSStringFromSelector(_cmd));
}
@finally
{
[fetchRequest release];
}
}
NSManagedObject* myManagedObject = fetchResults.lastObject;
// We get the dictionary here
NSDictionary *dictionary = [taskDictionary objectForKey:lookUpKey];
for(NSString *subKey in dictionary)
{
if([key isEqualToString:@"name"])
{
myManagedObject.name = [dictionary objectForKey:subKey];
}
else if([key isEqualToString:@"phone"]
{ //....Update the value...// }
}
}
}
现在在我的辅助线程类中,我在辅助线程的 saveContext 方法中有上面列出的数据处理逻辑。如果您在上面看到,那么我会保存我的主线程 MOC,然后才在我的线程中执行 NSFetchRequest。我还确保在执行保存之后和在我的辅助线程中执行 NSFetchRequest 之前,主 MOC 中没有更新的对象。