gpt4 book ai didi

ios - AFJSONRequestOperation 不更新 block 外的内容

转载 作者:行者123 更新时间:2023-11-28 20:18:27 26 4
gpt4 key购买 nike

我正在尝试使用 AFJSONRequestOperation 从 JSON 提要中提取少量数据。

以下代码可以很好地提取 url,并且在打印 stringURL 时,它会打印出正确的 url。但是,我尝试了几种不同的方法将 url 分配给 block 范围之外的新变量。无论我是尝试将生成的 url 分配给另一个全局 NSURL(确保使用 __block)还是尝试将其添加到数组中,它似乎没有及时更新以打印在 NSLog 中输出。我怀疑这是因为操作尚未完成。在调用 NSLog([streamUrls objectAtIndex:0]); 之前,如何确保操作已完成?

这是我使用的代码。

    NSURL *url = [contentUrls objectAtIndex:indexPath.row];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSONSound) {

NSString *stringURL = [NSString stringWithFormat:@"%@",
JSONSound[@"stream_url"], nil];

NSURL *streamURL = [NSURL URLWithString:stringURL];
NSLog(stringURL);
[streamUrls addObject:streamURL];
[self.collectionView reloadData];
} failure:nil];
[operation start];

NSLog([streamUrls objectAtIndex:0]);

编辑:[self.collectionView reloadData]; 这一行似乎没有影响到这种情况。

最佳答案

要确保在调用任何代码之前操作已完成,您可以使用 AFJSONRequestOperation 的成功 block ,这就是您将对象添加到 streamUrls 时所做的:

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSONSound) {
NSString *stringURL = [NSString stringWithFormat:@"%@",
JSONSound[@"stream_url"], nil];

NSURL *streamURL = [NSURL URLWithString:stringURL];
NSLog(stringURL);
[streamUrls addObject:streamURL];
[self.collectionView reloadData];
NSLog([streamUrls objectAtIndex:0]);
} failure:nil];

reloadData 不影响数据源。它只是刷新基于数据源显示的 Collection View (无论数据源是否更新)。

关于ios - AFJSONRequestOperation 不更新 block 外的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16931633/

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