gpt4 book ai didi

ios - 从嵌套完成 block 返回值

转载 作者:行者123 更新时间:2023-11-28 17:30:46 31 4
gpt4 key购买 nike

我有一个完成 block ,它采用一个基于用户选择的动态参数,如下所示:

NSString *data = <some value based on user selection>;
[avc activity:data withBlock:^id _Nonnull{

}

此 block 的返回类型为 id。

我有另一个像这样的 block :

[self createItem:data completion:^(NSString * _Nullable item) {
//value of item is received here
}];

我想要实现的是:

NSString *data = <some value based on user selection>;
//This data is used in both the blocks
[avc activity:data withBlock:^id _Nonnull{
[self createItem:data completion:^(NSString * _Nullable item) {
return item; //Error here
}];
}

返回项目会抛出错误,因为内部 block 的返回类型是 void。我想要实现的是,当内部 block 收到 item 中的值时,它应该将它返回到外部 block 。

我试过像这样使用调度组:

NSString *data = <some value based on user selection>;
//This data is used in both the blocks
[avc activity:data withBlock:^id _Nonnull{
__block NSString *url = nil;
dispatch_group_t group = dispatch_group_create();
dispatch_group_enter(group);
[self createItem:data completion:^(NSString * _Nullable item) {
url = item;
dispatch_group_leave(group);
}];
dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
return url
}

这是行不通的。应用程序在等待语句后无限期卡住。

有什么方法可以实现我的目标吗?

最佳答案

[[NSOperationQueue new] addOperationWithBlock:^{
NSString *data; // <some value based on user selection>;
[avc activity:data withBlock:^id _Nonnull{
__block NSString *url = nil;
dispatch_semaphore_t finished = dispatch_semaphore_create(0);
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
[self createItem:data completion:^(NSString * _Nullable item) {
url = item;
dispatch_semaphore_signal(finished);
}];
}];
dispatch_semaphore_wait(finished, DISPATCH_TIME_FOREVER);
return url
}];
}];

关于ios - 从嵌套完成 block 返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52725127/

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