gpt4 book ai didi

ios - 如何在 GET 请求之外使用变量?

转载 作者:行者123 更新时间:2023-11-29 10:48:18 25 4
gpt4 key购买 nike

我愿意:

  • 在 GET 请求之前初始化变量 (AFNetworking)
  • 赋值给请求里面的变量成功
  • 请求完成后使用变量

我得到的错误:

  • 在 GET 请求之后尝试对变量执行某些操作时,它中断了,声称该变量还没有值

下面是我的代码,我该如何解决这个问题?

- (IBAction)synchronisePressed {
//Would like to initialise a variable here
__block NSArray *received;
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:@"http://foo.com/foo/"
parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
//Assign responseObject to received object
received = responseObject;
NSLog(@"Woo: %@", @"got here");
}

failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
//Now outside of request, so use array in some way
[foo received];
}

最佳答案

问题不在代码或请求中。问题是 AFNetworking 的 GET 方法是异步的,而您正试图同步使用它。

这意味着 GET 方法将开始工作并在后台运行,其余代码将照常运行。只有当 GET 请求完成时, block 中的代码才会运行。

此代码可以是 1 秒或 30 秒或您开始请求后的任意时间。

在你的行 [foo received]; 之前放入一个 NSLog

日志的顺序是这样的...

1. Created NSArray called received.
2. Pass NSArray called received to method foo.
// some time later
3. AFNetworking GET request finished.
4. Assign value from the GET request to the NSArray called received.

在这种情况下,您需要做的是将您的调用置于完成 block 内的 [foo received];

像这样的……

- (IBAction)synchronisePressed
{
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

[manager GET:@"http://foo.com/foo/"
parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
//Assign responseObject to received object
NSArray *received = responseObject;
NSLog(@"Woo: %@", @"got here");
[foo received];
}

failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
}

现在你会得到...

1. Created NSArray called received.
// some time later
2. AFNetworking GET request finished.
3. Assign value from the GET request to the NSArray called received.
4. Pass NSArray called received to method foo.

关于ios - 如何在 GET 请求之外使用变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21579551/

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