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

时间:2014-02-05 14:07:21

标签: ios iphone objective-c networking afnetworking

我想

  • 在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];
}

1 个答案:

答案 0 :(得分:2)

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

这意味着GET方法将开始工作并在后台工作,其余代码将继续正常运行。只有当GET请求完成后,块内的代码才会运行。

此代码为1秒或30秒或您开始请求后的任何时间。

NSLog行前加[foo received];

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

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.

在这种情况下,您需要做的是将[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.