AFNetworking + AFHTTPRequestOperation 无法保存数组
AFNetworking + AFHTTPRequestOperation not being able to save Array
所以我试图在线访问一个 json 文件,当我 运行 使用 AFHTTPRequestOperation 方法完成块时,我可以获取 JSON 文件的内容。但是当我尝试在完成块之外使用 NSLog 时,它变为空。我想知道为什么会这样,我将如何解决这个问题。以下是我目前的代码:
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCredential:credentials];
[operation setResponseSerializer:[AFJSONResponseSerializer alloc]];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Success %@", responseObject);
jsonOutputData = [NSMutableArray arrayWithObject:responseObject];
self.newsFeedArray = [NSMutableArray arrayWithArray:[jsonOutputData copy]];
}failure:^(AFHTTPRequestOperation *operation, NSError *error){
NSLog(@"Failure: %@", error);
}];
[manager.operationQueue addOperation:operation];
NSLog(@"%@", self.newsFeedArray);
成功的 NSLog 显示 JSON,但 self.newsFeedArray 的 NSLog 显示(空)。我只是想知道为什么会这样。如果您需要更多说明,请告诉我。任何帮助,将不胜感激!
谢谢!
异步调用成功和失败块。所以 self.newsFeedArray
在最后一次 NSLog
调用时还没有设置,因为操作还没有完成。
您可以等待操作完成(例如,[operation waitUntilFinished]
)但您几乎肯定不想这样做,尤其是在主线程上。而是让完成块触发所需的行为。
所以我试图在线访问一个 json 文件,当我 运行 使用 AFHTTPRequestOperation 方法完成块时,我可以获取 JSON 文件的内容。但是当我尝试在完成块之外使用 NSLog 时,它变为空。我想知道为什么会这样,我将如何解决这个问题。以下是我目前的代码:
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCredential:credentials];
[operation setResponseSerializer:[AFJSONResponseSerializer alloc]];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Success %@", responseObject);
jsonOutputData = [NSMutableArray arrayWithObject:responseObject];
self.newsFeedArray = [NSMutableArray arrayWithArray:[jsonOutputData copy]];
}failure:^(AFHTTPRequestOperation *operation, NSError *error){
NSLog(@"Failure: %@", error);
}];
[manager.operationQueue addOperation:operation];
NSLog(@"%@", self.newsFeedArray);
成功的 NSLog 显示 JSON,但 self.newsFeedArray 的 NSLog 显示(空)。我只是想知道为什么会这样。如果您需要更多说明,请告诉我。任何帮助,将不胜感激!
谢谢!
异步调用成功和失败块。所以 self.newsFeedArray
在最后一次 NSLog
调用时还没有设置,因为操作还没有完成。
您可以等待操作完成(例如,[operation waitUntilFinished]
)但您几乎肯定不想这样做,尤其是在主线程上。而是让完成块触发所需的行为。