gpt4 book ai didi

ios - 应用卡在 dispatch_async 中

转载 作者:行者123 更新时间:2023-11-29 03:21:47 26 4
gpt4 key购买 nike

这是我的代码:

        LoadViewController *loadingViewController = [[LoadViewController alloc] initWithNibName:@"LoadViewController" bundle:nil];
[self.view addSubview:loadingViewController.view];

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) , ^{
[Util deleteAllObjects:@"Unit"];
for (NSDictionary *eachUnit in serviceData) {
//insert in DB
AppDelegate* appDelegate = [AppDelegate sharedAppDelegate];
NSManagedObjectContext *context = appDelegate.managedObjectContext;
Unit *unit = [NSEntityDescription insertNewObjectForEntityForName:@"Unit" inManagedObjectContext:context];

unit.id_unidade = [eachUnit objectForKey:@"id"];
unit.title = [eachUnit objectForKey:@"title"];
unit.image = [eachUnit objectForKey:@"image"];
unit.address = [eachUnit objectForKey:@"address"];
unit.desc = [eachUnit objectForKey:@"desc"];
unit.coord = [eachUnit objectForKey:@"coord"];

NSError *error;

if (![context save:&error]) {
NSLog(@"Ops,fail: %@", [error localizedDescription]);
}
}
NSLog(@"before");
[self fillUnits];
NSLog(@"after");

dispatch_async(dispatch_get_main_queue(), ^(void) {
NSLog(@"reload");
[self.tableView reloadData];
[loadingViewController.view removeFromSuperview];
NSLog(@"after reload");

});
});

它显示到 NSLog(@"after"),但永远不会显示到 NSLog(@"reload")。有什么线索吗??

最佳答案

在完成处理程序中,您需要确保发送到托管对象或托管对象上下文的所有方法都使用 performBlock: 在各自的执行上下文上执行或 performBlockAndWait::

    NSManagedObjectContext *context = appDelegate.managedObjectContext;
[context performBlockAndWait:^{
Unit *unit = [NSEntityDescription insertNewObjectForEntityForName:@"Unit" inManagedObjectContext:context];

unit.id_unidade = [eachUnit objectForKey:@"id"];
unit.title = [eachUnit objectForKey:@"title"];
unit.image = [eachUnit objectForKey:@"image"];
unit.address = [eachUnit objectForKey:@"address"];
unit.desc = [eachUnit objectForKey:@"desc"];
unit.coord = [eachUnit objectForKey:@"coord"];

NSError *error;
if (![context save:&error]) {
NSLog(@"Ops,fail: %@", [error localizedDescription]);
}
}];

如果您的托管对象将在主线程中访问,则执行上下文必须等于主线程。

您可以在 Apple 文档中阅读更多信息:NSManagedObjectContext Reference ,尤其是“并发”一章。

关于ios - 应用卡在 dispatch_async 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20997946/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com