gpt4 book ai didi

iphone - AFJSONRequestOperation 数组填充但不能成功 block 之外的 NSLog 内容

转载 作者:行者123 更新时间:2023-12-01 19:14:48 26 4
gpt4 key购买 nike

The following code is taken from this tutorial

我以前使用过这个片段,但我以前从未注意到这个问题。数组内容的 NSLog 在委托(delegate)方法中打印,但不在成功 block 之外的 viewDidLoad 中。我需要一种将 JSON 数据保存到数组中的方法,以便在代码的其他地方使用。我还应该补充一点,我没有使用 UITableView 来显示我的数据。我错过了什么或者我该如何做到这一点?

这不会打印 JSON 内容,认为它确实填充了数组:

#import "AFNetworking.h"
...
- (void)viewDidLoad {
...

self.movies = [[NSArray alloc] init];
NSURL *url = [[NSURL alloc] initWithString:@"http://itunes.apple.com/search?term=harry&country=us&entity=movie"];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
self.movies = [JSON objectForKey:@"results"];
[self.activityIndicatorView stopAnimating];
[self.tableView setHidden:NO];
[self.tableView reloadData];

} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(@"Request Failed with Error: %@, %@", error, error.userInfo);
}];

[operation start];

NSLog(@"self.movies %@",self.movies); // does not print
...
}

这会打印 JSON 内容:我只使用 numberOfRowsInSection 作为 NSLog 语句的单独位置。
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (self.movies && self.movies.count) {
NSLog(@"self.movies %@",self.movies); // prints
...
}

最佳答案

您正在启动异步操作,然后立即尝试打印出内容。移动您的第一个NSLog语句进入成功 block 。

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
//the following lines of code execute after the response arrives
self.movies = [JSON objectForKey:@"results"];
NSLog(@"self.movies %@",self.movies);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(@"Request Failed with Error: %@, %@", error, error.userInfo);
}];
[operation start];
//this line of code executes directly after the request is made,
//and the response hasn't arrived yet
NSLog(@"I probably don't have the response yet");

关于iphone - AFJSONRequestOperation 数组填充但不能成功 block 之外的 NSLog 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14064503/

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