繁体   English   中英

AFJSONRequestOperation不更新块外的内容

[英]AFJSONRequestOperation not updating content outside of block

我正在尝试使用AFJSONRequestOperation从JSON提要中获取和平的数据。

以下代码可以很好地提取url,并且在打印stringURL时,它会打印正确的url。 但是,我尝试了几种不同的方法来将url分配给新变量,而不是块的范围。 无论是尝试将结果URL分配给另一个全局NSURL (确保使用__block )还是尝试将其添加到数组中,似乎都无法及时更新以在NSLog中打印出来。 我怀疑这是因为操作尚未完成。 在调用NSLog([streamUrls objectAtIndex:0]);之前,如何确保操作已完成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的成功块,这是将对象添加到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不会影响数据源。 它只是刷新基于数据源显示的收集视图(无论数据源是否已更新)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM