2014-02-05 69 views
1

我想如何在GET請求之外使用變量?

  • 一個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]; 
} 
+0

[Objective-C的塊和變量的作用域(可能重複http://stackoverflow.com/questions/9407675/objective-c-blocks-and-variable-scope) – Larme

回答

2

問題不在代碼或請求中。問題是AFNetworking的GET方法是異步的,並且您試圖同步使用它。

這意味着GET方法將開始工作並坐在後臺工作,其餘代碼將繼續正常工作。只有GET請求完成後,塊內的代碼纔會運行。

此代碼爲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. 

你需要在這種情況下,做的是把你的電話給[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. 
+0

不知道爲什麼我沒有想到這一點,我正在繞圈工程。謝謝:)作爲一方,需要多少代碼才能實現同步?如果可能的話。 –

+0

我會避免同步網絡代碼。通過同步執行它將阻​​止主UI線程。這意味着如果您的網絡請求需要10秒鐘,則應用程序將完全凍結10秒。如果您的應用程序執行任何需要「人爲察覺」的時間量,那麼請異步執行該任務。 – Fogmeister