gpt4 book ai didi

objective-c - dispatch_group_t - EXC_BAD_INSTRUCTION

转载 作者:行者123 更新时间:2023-12-04 12:52:12 26 4
gpt4 key购买 nike

这是我第一次使用 dispatch_group_t,我犯了一个简单的错误。 dispatch_group_notify 在任何异步调用返回之前被调用,因此甚至在第一个 dispatch_group_leave(group) 之前被调用,然后抛出一个 EXC_BAD_INSTRUCTION

但是,我不知道为什么会这样。

dispatch_queue_t queue =      dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_group_t group = dispatch_group_create();

dispatch_group_async(group, queue, ^{
[self getCategoriesMainWithParameters:nil withSuccess:^(NSArray *objects) {
[categoriesMain addObjectsFromArray:objects];
dispatch_group_leave(group);
} failure:^(NSError *error) {
groupError = error;
dispatch_group_leave(group);
}];
});

dispatch_group_async(group, queue, ^{
[self getCategoriesSubWithParameters:nil withSuccess:^(NSArray *objects) {
[categoriesSub addObjectsFromArray:objects];
dispatch_group_leave(group);
} failure:^(NSError *error) {
groupError = error;
dispatch_group_leave(group);
}];
});

dispatch_group_async(group, queue, ^{
[self getCategoriesProductWithParameters:nil withSuccess:^(NSArray *objects) {
[categoriesProduct addObjectsFromArray:objects];
dispatch_group_leave(group);
} failure:^(NSError *error) {
groupError = error;
dispatch_group_leave(group);
}];
});

dispatch_group_notify(group,dispatch_get_main_queue(),^{
...
});

最佳答案

dispatch_group_async 函数在分派(dispatch) block 时自动“进入”组,并在分派(dispatch) block 完成时自动“离开”。但是您再次调用 dispatch_group_leave,所以您最终会调用太多的“离开”,从而导致您描述的错误。

应该调用 dispatch_group_async(所有“进入”和“离开”调用都已为您完成),或者在异步调用之前手动调用 dispatch_group_enter 并调用 dispatch_group_leave 在异步过程的完成处理程序中。

在这种情况下,因为您在分派(dispatch) block 内调用异步任务,dispatch_group_async 模式将不起作用。您希望在调用异步方法之前手动 dispatch_group_enter,然后像您一样让完成处理程序调用 dispatch_group_leave。当每个“进入”都与“离开”相匹配时,该组将收到通知。而且因为您调用的方法已经是异步的,所以您根本不需要使用 dispatch_asyncdispatch_group_async

因此,它可能看起来像:

dispatch_group_t group = dispatch_group_create();

dispatch_group_enter(group);
[self getCategoriesMainWithParameters:nil withSuccess:^(NSArray *objects) {
[categoriesMain addObjectsFromArray:objects];
dispatch_group_leave(group);
} failure:^(NSError *error) {
groupError = error;
dispatch_group_leave(group);
}];

dispatch_group_enter(group);
[self getCategoriesSubWithParameters:nil withSuccess:^(NSArray *objects) {
[categoriesSub addObjectsFromArray:objects];
dispatch_group_leave(group);
} failure:^(NSError *error) {
groupError = error;
dispatch_group_leave(group);
}];

dispatch_group_enter(group);
[self getCategoriesProductWithParameters:nil withSuccess:^(NSArray *objects) {
[categoriesProduct addObjectsFromArray:objects];
dispatch_group_leave(group);
} failure:^(NSError *error) {
groupError = error;
dispatch_group_leave(group);
}];

dispatch_group_notify(group,dispatch_get_main_queue(),^{
...
});

关于objective-c - dispatch_group_t - EXC_BAD_INSTRUCTION,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28467673/

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