我是 dispatch_queue 的新手,尝试在后台保存到 CoreData 时遇到了问题。我已阅读 CoreData 编程指南,并且NSManagedObjectContext
在后台线程中创建了一个单独的。当我在测试项目中执行一个简单的循环来创建NSManagedObject
s 时,我没有任何问题,创建了对象并使用 将NSManageObjectContextDidSaveNotification
更改传达给主线程。
我相信我的问题在于我对 GCD 的无知。我正在解析 XML,parserDidEndDocument:
我需要在不阻塞 UI 的情况下将数据保存到 CoreData。每当使用这个块时,我的应用程序内存开始不受控制地滚雪球,直到最后我得到Terminated app due to memory pressure
.
注意:我使用 AppDelegate 的单例来保存我的NSPersistentStoreCoordinator
东西,而 stuffToSave 是NSMutablearray
由我的解析器创建的。
任何方向将不胜感激。这两天我一直在打我的头!
-(void)parserDidEndDocument:(NSXMLParser *)parser
dispatch_queue_t backgroundQ = dispatch_queue_create("com.example.myapp", NULL);
__block AppDelegate *app= [[UIApplication sharedApplication]delegate];
__block NSMutableArray *array = self.stuffToSave;
dispatch_async(backgroundQ, ^(void){
NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
context.persistentStoreCoordinator = [app persistentStoreCoordinator];
HNField *field = [HNField fieldWithField_id:[NSNumber numberWithInt:0] inContext:context];
//initalize array if needed
if (!field.arrayOfPolylines) field.arrayOfPolylines = [[NSMutableArray alloc]init];
//add polyline to array to save in database
for (id obj in array) {
if ([obj isKindOfClass:[HNPolyline class]]) {
HNPolyline *theLine = (HNPolyline *)obj;
[field.arrayOfPolylines addObject:theLine];
}else if ([obj isKindOfClass:[HNParserPoint class]]){
HNPoint *point = [HNPoint createAPointWithContext:context];
HNParserPoint *pPoint = (HNParserPoint *)obj;
point.point_id = pPoint.point_id;
point.lat = pPoint.lat;
point.lng = pPoint.lng;
point.yield = pPoint.yield;
point.farm_id = self.farm_id;
point.field_id = self.field_id;
point.inField = field;
//add every point in database
[field addFieldPointsObject:point];
}
}
NSError *error;
[context save:&error];
});
self.stuffToSave = nil;
self.parser = nil;
}
编辑1:
我正在NSManageObjectContextDidSaveNotification
从与我正在解析的地方不同的班级收听。在viewDidLoad
我有:
// observe the ParseOperation's save operation with its managed object context
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(didSave:)
name:NSManagedObjectContextDidSaveNotification
object:nil];
然后我使用 Apple 的“ThreadedCoreData”示例中的以下内容。
-(void)didSave:(NSNotification *)notification{
if (notification.object != [self.app managedObjectContext]) {
NSLog(@"not main context");
[self performSelectorOnMainThread:@selector(updateMainContext:) withObject:notification waitUntilDone:NO];
}else{
NSLog(@"b Thread: %@",[NSThread currentThread]);
NSLog(@"main context");
}
}
// merge changes to main context
- (void)updateMainContext:(NSNotification *)notification {
assert([NSThread isMainThread]);
[[self.app managedObjectContext] mergeChangesFromContextDidSaveNotification:notification];
NSLog(@"did save");
}