我遇到一些麻烦,使用后台线程在UIManagedDocument
/Core Data
更新数据。具体来说,我使用NSFetchResultsController
更新基于来自后台线程的地理编码数据的地图注释(在合并回我的主要MOC之后),但由于UIManagedDocument
向数据库和/或其数据提交数据的方式多个MOC(父母和小孩)。如果我关闭应用程序并重新打开,则注释被填充,因此对持久存储的提交在某个时间点发生,但是我不清楚如何强制执行这样的提交,从而更新NSFetchResultsController
。下面是一些代码:核心数据:NSManagedObjectContext中,NSFetchResultsController和UIManagedDocument
后台线程更新商务部:
- (void) populateGPSCoordsInClubsInContext: (NSManagedObjectContext *) mainCtx
{
dispatch_queue_t MapFetchQ = dispatch_queue_create("Google Map Data Fetcher", NULL);
dispatch_async(MapFetchQ, ^{
NSManagedObjectContext * ctxThread = [[NSManagedObjectContext alloc] init];
[ctxThread setPersistentStoreCoordinator:mainCtx.persistentStoreCoordinator];
NSFetchRequest * request = [NSFetchRequest fetchRequestWithEntityName:@"Club"];
request.predicate = [NSPredicate predicateWithFormat:@"inRegion.name=%@", self.name];
NSError *error = nil;
NSArray * clubs = [ctxThread executeFetchRequest:request error:&error];
NSLog(@"[%@] Fetching map data. Club count is %d", self.name, [clubs count]);
int delayCounter = 0;
for(Club * club in clubs)
{
if(![club.hasCoord boolValue] && club != nil)
{
delayCounter++; // to deal with google maps api's DoS protection
[club setLongitudeAndLattitudeFromGoogle];
NSError * error;
if(![ctx save:&error])
NSLog(@"[%@] Problem saving region to database.", self.name);
}
if(delayCounter == 8)
{
[NSThread sleepForTimeInterval:(NSTimeInterval)2.0];
delayCounter = 0;
}
}
});
dispatch_release(MapFetchQ);
}
当这些节省被称为,我抢在主线程的通知(在我的应用程序委托),像这样:
- (void) contextDidSave: (NSNotification *) notification
{
NSManagedObjectContext * ctx = [self.clubsDB managedObjectContext];
[ctx mergeChangesFromContextDidSaveNotification:notification];
NSArray * updates = [[notification.object updatedObjects] allObjects];
for(Club * club in updates) // This never fires because updates never has objects
{
NSLog(@"*********** %@", club.name);
}
NSLog(@"[%@] %@", [self class], NSStringFromSelector(_cmd));
}
而且我已经把我的获取结果控制器像这样(谓语是正确的,结果与应用程序重启数据已提交到存储后预计):
-(void) setupFRC
{
NSFetchRequest * request = [NSFetchRequest fetchRequestWithEntityName:@"Club"];
request.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES]];
request.predicate = [NSPredicate predicateWithFormat:@"inRegion.name=%@ AND hasCoord=%@",[self.clubsDB regionTitleAsString], [NSNumber numberWithBool:YES]]; // Follow the relationshop and only display clubs from THIS region.
//request.predicate = [NSPredicate predicateWithFormat:@"inRegion.name=%@",[self.clubsDB regionTitleAsString]];
self.debug = YES;
self.fetchedResultsController =
[[NSFetchedResultsController alloc] initWithFetchRequest:request
managedObjectContext:self.clubsDB.managedObjectContext
sectionNameKeyPath:nil
cacheName:nil];
}
有关如何更新相应的MOC以使获取的结果控制器按所需行为的任何想法?
任何人都可以吗?完全卡住..:/ – Andrew 2012-03-26 20:00:44