我想:
我得到的错误:
以下是我的代码,我该如何解决这个问题?
- (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 :(得分: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.